我有三个表,machines
存放自动售货机,products
存放所有可能的产品,machines_products
是两者的交集,给出特定机器中每个产品系列的库存数量。如果机器中没有库存产品,则第三个表中没有相应的行。
DESCRIBE machines_products;
+------------+------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+------------+------------------+------+-----+---------+-------+
| machine_id | int(10) unsigned | NO | PRI | 0 | |
| product_id | int(10) unsigned | NO | PRI | 0 | |
| quantity | int(10) unsigned | NO | | 0 | |
+------------+------------------+------+-----+---------+-------+
每种产品都有一个类别(想想巧克力棒和饮料瓶),机器知道它可以销售什么类别的产品。我想要该类别的所有产品的结果表,以及特定机器的数量。我已经做到了:
SELECT products.*, SUM(quantity) qty
FROM products
LEFT JOIN machines_products USING (product_id)
WHERE machine_id=m AND category_id=c
GROUP BY product_id;
问题是,这会过滤掉所有没有数量的行,而我想要的是左表中的所有行,如果没有对应的,则 qty
列中的 NULL/0右侧表格中的行。
顺便说一句:这不是家庭作业问题!我 30 岁,坐在办公室里:o)
最佳答案
SELECT p.*
, SUM(mp.quantity) AS qty
FROM products p
LEFT JOIN machine_products mp
ON mp.product_id = p.product_id
AND mp.machine_id = m --- this condition moved from WHERE to ON
WHERE p.category_id = c
GROUP BY p.product_id
关于mysql - 强制连接第一个表中的所有行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6609059/