连接和输出 - 使用SELECT DISTINCT

时间:2016-03-06 20:23:21

标签: mysql mysql-workbench

我想要一些关于如何在不使用Group By命令的情况下为以下内容编写SQL的指导?

假设我有下表:

Product
PrdNo|PrdName
1|Mouse
2|Keyboard
3|Monitor
4|Speakers
5|Cpu

OrderList
OrdNo|PrdNo|Qty
101|4|2
102|3|4
103|2|1
104|1|5
105|4|3
106|5|1
107|2|4

Orders
OrdNo|OrdState
101|MD
102|CA
103|CA
104|VA
105|CA
106|NY
107|CA

如何显示订单状态为CA的以下内容?并按产品名称升序排序。使其仅打印唯一(不同)的产品名称。并且不要使用Group By命令。

PrdName|PrdNo||OrdState   
Keyboard|2|CA
Monitor|3|CA
Speakers|4|CA

1 个答案:

答案 0 :(得分:1)

您需要将表格加在一起并应用DISTINCT

SELECT DISTINCT p.PrdNo, p.PrdName, o.OrdState
FROM Product AS p
INNER JOIN OrderList AS ol ON p.PrdNo = ol.PrdNo
INNER JOIN Orders AS o ON o.OrdNo = ol.OrdNo
WHERE o.OrdState = 'CA'
ORDER BY PrdName

Demo here