0

我想看看客户从给定制造商那里订购了什么。

我有这些表(带列):

  • 项目(item_num、order_num、stock_num、manu_code、数量等)
  • 库存(stock_num、manu_codedescription、unit_price 等)
  • 订单(order_num、order_date、customer_num、ship_instruct 等)
  • 客户(customer_num、fname、lname、company、address1 等)

这是我现在的查询,但我相信它会返回某种叉积:

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

我究竟做错了什么?

4

4 回答 4

1

FROM items i, stock s, customer c对所涉及的三个表进行笛卡尔连接,但您WHERE对该笛卡尔连接的限制很少。

如果你做一些更明确的加入,你将大大减少重复并更正确地表达你想要做的事情。使用INNER JOINS和 正确的连接条件,而不是仅仅在 . 之后列出所有表FROM。示例:(还有更多这样的标准,您需要将其应用于 JOINS,但这是一个示例) INNER JOIN stock ON stack.manu_code = items.manu_code:。

最后,您可以使用SELECT DISTINCTorGROUP BY来进一步减少重复。但是,如果您JOIN使用正确的 JOIN 标准获得了明确的 s,那么您不应该有太多的重复项。

于 2013-01-21T18:29:02.493 回答
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'
于 2013-01-21T18:32:15.090 回答
0

这应该工作:

        选择 concat(a.fname, " ", a.lname ) 作为名称
                        , d. 描述为 desc
        来自客户
        内部连接订单 b
            a.customer_num = b.customer_num
        内连接项 c
            在 b.order_num = c.order_num
        内连接股票 d
            在 c.manu_code = d.manu_code
        其中 c.manu_code 像 'ANZ'
        按名称分组,desc

于 2013-01-22T06:38:31.817 回答
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';
于 2013-01-22T16:59:36.383 回答