如何从两个表中获取信息?

问题描述:

我有一个名为superstore和4个表的数据库。 enter image description here如何从两个表中获取信息?

-- Q5: Pull all the order details of Product 
-- (ID: 657768) got sold at a discount rate of 0.06 
SELECT * FROM superstore.orders JOIN 
superstore.product ON 
superstore.orders.ProductID=superstore.product.ProductID 
WHERE 
superstore.product.ProductID='657768' AND Discount='0.06'; 

这将返回一个空记录。我该如何解决它?

+0

你不需要围绕数字字段单引号 - 但mysql应该做一个隐式转换。尝试删除连接以查看是否从订单单独返回任何内容,然后向产品添加左连接以查看是否从产品重新生成null。 –

SELECT * 
FROM Product p 
JOIN Orders o ON o.ProductID = p.ProductID 
WHERE 
    p.ProductID = '657768' AND 
    Discount = 0.06; 

在SELECT查询中使用列名而非“*”使用列名非常重要,因为如果您的表有数千个记录,则它变得很慢。

SELECT 
    p.ProductID,p.ProductName,p.ProductCategory,p.ProductSubCategory, 
    p.ProductContainer,p.ProductBaseMargin 
    FROM Product p 
    JOIN Orders o ON o.ProductID = p.ProductID 
    WHERE p.ProductID = '657768' AND o.Discount=0.06