带有内部联接的Where子句不适用于订单表

问题描述 投票:0回答:1

我有下表(括号内的列):

  • 产品(产品ID,产品名称,类别ID)
  • categories(categoryID,categoryName)
  • customers(customerID,customerName)
  • 订单(客户ID,create_at,产品ID)

我可以成功地使用内部联接显示所有订单详细信息,并包括产品和客户名称。

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'

如何显示仅属于特定类别的产品的订单?

mysql inner-join where-clause
1个回答
3
投票

您必须加入表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';

categoryIDproducts中都必须有类似categories的列。有时,一个产品可能属于多个类别。在这种情况下,必须有另一个表将产品链接到类别。

© www.soinside.com 2019 - 2024. All rights reserved.