我尝试根据第二个表的寄存器从一个表中进行选择
我使用4张桌子
table Products
Product_Id | Product_Name | Product_Value | Category_Id
1 | Ball | 10 | 1
2 | Pen | 2 | 2
3 | Eraser | 1 | 1
table Categories
Category_Id | Category_Name
1 | Acessories
2 | Others
table Customers
Customer_Id | Customer_Name
1 | John
2 | Peter
table Sells
Sell_Id | Product_Id | Customer_Id | Sell_Date
1 | 1 | 1 | 2012-01-01
2 | 2 | 1 | 2012-01-02
所以我想做一个选择,向客户展示他买的东西
像
John Historic
Product Name Category Name Date
Ball Accessories 2012-01-01
Pen Others 2012-010
在最后,我将从3个不同的表格中显示信息
我尝试使用INNER JOIN和LEFT JOIN,但没有成功。
感谢您的帮助。
答案 0 :(得分:5)
分解:你想要的第一件事是产品名称:
SELECT Product_Name FROM Products
我们如何获得该类别?加入吧!
SELECT Products.Product_Name, Categories.Category_Name
FROM Products JOIN Categories ON Products.Category_Id = Categories.Category_Id
越来越近了!是时候引入订单历史了:
SELECT Products.Product_Name, Categories.Category_Name, Sells.Sells_Date
FROM Products
JOIN Categories ON Products.Category_Id = Categories.Category_Id
JOIN Sells ON Sells.Sells_Id = Products.Product_Id
现在我们可以引入名称,并过滤到John:
SELECT Products.Product_Name, Categories.Category_Name, Sells.Sells_Date
FROM Products
JOIN Categories ON Products.Category_Id = Categories.Category_Id
JOIN Sells ON Sells.Sells_Id = Products.Product_Id
JOIN Customers ON Sells.Customer_Id = Customers.Customer_Id
WHERE Customers.Customer_Name = 'John'
在你的脑海中一步一步。随时随地构建每个部分的查询。
LEFT JOIN
是您处理缺失数据的方式。它返回“left”表中的行,如果NULL
子句不匹配,则将ON
放入“right”表的字段中。
例如,如果John购买的产品没有类别(Product.Category_Id
为NULL
),则使用JOIN
将不会返回该购买记录,因为没有匹配的类别{ {1}} Category_Id
。在这种情况下,您可以Null
,在结果集中,LEFT JOIN Categories
也是Category_Name
。
答案 1 :(得分:2)
SELECT
Customers.Customer_Name as 'Customer Name',
Products.Product_Name as 'Product Name',
Categories.Category_Name as 'Category Name',
Sells.Sell_Date as 'Date Sold'
FROM Customers
INNER JOIN Sells on Sells.Customer_Id = Customers.Customer_Id
INNER JOIN Products ON Products.Product_Id = Sells.Sell_Id
INNER JOIN Categories ON Categories.Category_Id = Products.Category_ID;
如果要为单个人提取历史记录,可以使用WHERE子句:
WHERE Customers.Customer_Id = 1
...或
WHERE Customers.Customer_Name = 'John'
答案 2 :(得分:1)
只需在所有这些表上使用JOIN并选择您想要的任何内容:
SELECT
p.Product_Name, c.Category_Name, s.Sell_Date
FROM
Customers cu JOIN Sells s ON cu.id = s.Customer_Id
JOIN Products p ON p.id = s.Product_Id
JOIN Categories c ON p.Category_Id = c.id
WHERE
cu.Customer_Name = "John"
答案 3 :(得分:1)
JOIN
是正确的:
SELECT Products.Product_Name, Categories.Category_Name, Sells.Sell_Date
FROM Sells JOIN Products ON Sells.Product_Id = Products.Product_Id JOIN Categories ON Sells.Category_Id = Categories.Category_Id
WHERE Sells.Customer_Id = 1;
答案 4 :(得分:0)
SELECT Product_Name, Category_Name, Sell_Date
FROM Products, Categories, Sells
WHERE Sells.Customer_Id = 1
AND Sells.Product_Id = Products.Product_Id
AND Products.Category_Id = Categories.Category_Id;