【问题标题】:Where clause with inner join not working for orders table带有内部连接的 Where 子句不适用于订单表
【发布时间】:2020-04-11 13:59:50
【问题描述】:

我有以下表格(括号中的列):

  • 产品(productID, productName, categoryID)
  • categories(categoryID, categoryName)
  • 客户(客户 ID,客户名称)
  • 订单(customerID、create_at、productID)

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

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'

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

【问题讨论】:

  • 您忘记加入类别表了吗?
  • 我没有加入类别,因为 categoryID 未包含在订单表中。

标签: mysql inner-join where-clause


【解决方案1】:

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

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

【讨论】:

  • 糟糕。这确实有效!我的理解是,在内部连接中,每个条件都基于 from 表,在我的例子中是订单。感谢您的支持。
猜你喜欢
  • 2011-01-01
  • 2017-06-19
  • 2012-09-04
  • 1970-01-01
  • 2013-03-19
  • 2016-08-17
  • 1970-01-01
  • 1970-01-01
  • 2020-10-09
相关资源
最近更新 更多