我希望看到客户从特定制造商那里订购了什么产品。
我有这些表(带列):
这是我现在的查询,但我相信它会返回某种类型的交叉产品:
SELECT concat(c.fname," ", c.lname) AS fullname, s.description
FROM items i, stock s, customer c JOIN orders o
ON o.customer_num=c.customer_num
WHERE o.order_num=i.order_num AND i.manu_code = 'ANZ';
返回一个包含大量重复内容的大型列表(1000行),
Anthony Higgens | baseball gloves
Anthony Higgens | baseball gloves
. .
. .
. .
Kim Satifer | running shoes
我做错了什么?
答案 0 :(得分:1)
FROM items i, stock s, customer c
对所涉及的这三个表进行了笛卡尔联合,但您的WHERE
对该笛卡尔联接的限制很少。
如果你做了一些更明确的加入,你将会仔细减少重复,并更恰当地表达你想要做的事情。使用INNER JOINS
和正确的加入条件,而不是仅列出FROM
之后的所有表格。示例:(有更多此类条件,您需要应用于JOINS,但这是一个示例):INNER JOIN stock ON stack.manu_code = items.manu_code
。
最后,您可以使用SELECT DISTINCT
或GROUP BY
来进一步减少重复项。但是,如果你明确JOIN
的JOIN标准是正确的,那么你不应该有太多的重复。
答案 1 :(得分:0)
试试这个:
SELECT DISTINCT concat(c.fname," ", c.lname) AS fullname, s.description
FROM customer c
INNER JOIN orders o ON c.customer_num = o.customer_num
INNER JOIN items i ON o.order_num = i.order_num
INNER JOIN stock s on s.stock_num = i.stock_num
WHERE i.manu_code = 'ANZ'
答案 2 :(得分:0)
这应该有效:
SELECT concat(a.fname, " ", a.lname ) as name , d.description as desc FROM CUSTOMER a INNER JOIN ORDERS b on a.customer_num = b.customer_num INNER JOIN ITEMS c on b.order_num = c.order_num INNER JOIN STOCK d on c.manu_code = d.manu_code where c.manu_code like 'ANZ' group by name,desc
答案 3 :(得分:0)
谢谢大家,我认为现在正在运作:
SELECT DISTINCT concat(c.fname," ", c.lname) AS fullname, s.description
FROM customer c
INNER JOIN orders o ON c.customer_num = o.customer_num
INNER JOIN items i ON o.order_num = i.order_num
INNER JOIN stock s on s.stock_num = i.stock_num
WHERE i.manu_code = 'ANZ';