我有两个表products(id, name)
和products_cost(id, sid, cost)
。
我正在尝试获取总成本低于1000的产品清单,包括没有成本的产品。
我已经尝试过了:
SELECT a.name, SUM(b.cost) AS price
FROM products a
LEFT JOIN products_cost b
ON a.id = b.sid
GROUP BY a.name
HAVING SUM(b.cost)<1000;
上面的SQL仅给出了包含成本的产品名称列表,我希望输出列表中也包含不包含成本的产品名称。
答案 0 :(得分:2)
我认为您需要检查null
子句中的having
值:
SELECT p.name, SUM(pc.cost) AS price
FROM products p LEFT JOIN
products_cost pc
ON p.id = b.sid
GROUP BY p.name
HAVING SUM(pc.cost) < 1000 OR SUM(pc.cost) IS NULL;
请注意,我也固定了逻辑(salary
在SUM()
中没有意义)。我介绍了有意义的表别名-表名的缩写。
答案 1 :(得分:0)
使用子查询并加入
select p.*,a.s as cost from product p left join (
select pid,sum(cost) as s
from products_cost
group by pid
having s<1000 ) a on p.id=a.pid
答案 2 :(得分:0)
您还可以在IFNULL
子句中添加HAVING
表达式
SELECT a.name, SUM(b.cost) AS price
FROM products a
LEFT JOIN products_cost b
ON a.id = b.sid
GROUP BY a.name
HAVING SUM(IFNULL,b.cost,0)<1000;