我有下表(括号内的列):
我可以成功地使用内部联接显示所有订单详细信息,并包括产品和客户名称。
select products.productName, orders.create_at, customers.customerName
from orders
inner join products on orders.productID=products.productID
inner join customers on orders.customerID=customers.customerID;
现在,我只想显示产品属于“笔记本电脑”类别的订单。我的尝试如下:
select products.productName, orders.create_at, customers.customerName
from orders
inner join products on orders.productID=products.productID
inner join customers on orders.customerID=customers.customerID where categories.categoryName='laptop';
但是这不起作用,我认为这是因为where子句应基于属于orders表的列。
我得到的错误如下:
ERROR 1054 (42S22): Unknown column 'categories.categoryName' in 'where clause'
如何显示仅属于特定类别的产品的订单?
您必须加入表categories
:
select products.productName, orders.create_at, customers.customerName
from orders
inner join products on orders.productID=products.productID
inner join categories on categories.categoryID=products.categoryID
inner join customers on orders.customerID=customers.customerID
where categories.categoryName='laptop';
categoryID
和products
中都必须有类似categories
的列。有时,一个产品可能属于多个类别。在这种情况下,必须有另一个表将产品链接到类别。