mySQL从连接表中排除行

时间:2015-12-18 21:18:06

标签: mysql

我的脑袋最长。我有两个表,一个包括客户摘要,另一个包括他们购买的库存(购买的库存各自独立)。我想返回具有一定数量和符合特定标准的订单的客户信息。我以为我拥有它,但猜不是。

这是我到目前为止所拥有的:

SELECT a.customerTableStuff, SUM(b.quantity) 
FROM order_sum a, order_inv b 
WHERE a.ordernum = b.ordernum AND status = 2 
HAVING quantity <= 2 OR (quantity = 2 AND b.Code NOT LIKE 'C1%')
ORDER BY a.ordernum DESC

总和似乎有效,但是,Code Not Like就是问题所在。如果行中的另一个产品代码不同,则选择为true ... 我也试过加入并得到相同的结果。

提前致谢。

2 个答案:

答案 0 :(得分:0)

您的查询存在多个问题。我想你想要的东西:

SELECT a.customerTableStuff, SUM(b.quantity) as sumquantity
FROM order_sum a JOIN
     order_inv b 
     ON a.ordernum = b.ordernum AND status = 2 
GROUP BY a.customerTableStuff
HAVING sumquantity < 2 OR
       sum(case when b.code not like 'C1%' then b.quantity else 0 end) = 2
ORDER BY a.ordernum DESC;

评论:

  • 使用显式JOIN语法。简单规则:从不FROM子句中使用逗号。
  • 您需要GROUP BY
  • 您的HAVING条款是多余的。第二个条件是没有必要的。我猜你想要< 2作为第一个条件。
  • 请注意在查询中使用不合格的列别名。定义与列名称相同的别名(查询中为quantity)可能会导致意外结果。
  • 我不知道在b.code子句中having应该做什么。我做了一个猜测。

答案 1 :(得分:0)

让你尝试UNION

SELECT a.customerTableStuff, SUM(b.quantity) 
FROM order_sum a, order_inv b 
WHERE a.ordernum = b.ordernum AND status = 2 
HAVING quantity <= 2
ORDER BY a.ordernum DESC
UNION
SELECT a.customerTableStuff, SUM(b.quantity) 
FROM order_sum a, order_inv b 
WHERE a.ordernum = b.ordernum AND status = 2 
AND b.Code NOT LIKE 'C1%'
HAVING quantity = 2
ORDER BY a.ordernum DESC
相关问题