MySQL:只左连接一行并求和
是否可以在没有子查询的情况下只左连接一行 我需要获得产品统计数据,有些产品有多个组。 因此,产品数量不正确MySQL:只左连接一行并求和,mysql,sql,Mysql,Sql,是否可以在没有子查询的情况下只左连接一行 我需要获得产品统计数据,有些产品有多个组。 因此,产品数量不正确 SELECT COUNT(p.id) AS total_product, SUM(p.price) AS total_price FROM product p LEFT JOIN attribute_group a ON a.product_id = p.id WHERE p.created_at >= "2018-01-01" AND (a.id = 1 OR a.id = 2)
SELECT COUNT(p.id) AS total_product, SUM(p.price) AS total_price
FROM product p
LEFT JOIN attribute_group a ON
a.product_id = p.id
WHERE p.created_at >= "2018-01-01" AND (a.id = 1 OR a.id = 2)
GROUP BY p.id
LIMIT 0, 30;
product
id | price
1 | 100
2 | 150
3 | 250
attribute_group
id | product_id | title
1 | 1 | a1
2 | 1 | a2
3 | 2 | a3
4 | 3 | a4
应该是:
1| 100
但我得到:
2 | 200
您似乎想要所有属性为1和2的产品或其计数/总和。这里有一种方法:
SELECT COUNT(*) as num_products, SUM(p.price) as total_price
FROM product p
WHERE p.created_at >= '2018-01-01' AND
EXISTS (SELECT 1
FROM attribute_group ag
WHERE ag.product_id = p.id AND ag.id = 1
) AND
EXISTS (SELECT 1
FROM attribute_group ag
WHERE ag.product_id = p.id AND ag.id = 2
);
只需在没有分组的情况下进行左连接,你就会明白发生了什么。解释你的逻辑。你的问题并没有解释你想做什么,只是解释什么不起作用。Gordon Linoff>我需要按价格和属性选择产品的总价格。你应该用
或替换和,并添加日期condition@shukshin.ivan . . . 根据样本数据,和
似乎更合适。