查询未返回所有行
问题描述:
设置:查询未返回所有行
create table product_stock(product_id integer, qty integer, branch_id integer);
create table product(product_id integer, product_name varchar(255));
insert into product(product_id, product_name)
values(1, 'Apsana White DX Pencil');
insert into product(product_id, product_name)
values(2, 'Diamond Glass Marking Pencil');
insert into product(product_id, product_name)
values(3, 'Apsana Black Pencil');
insert into product_stock(product_id, qty, branch_id)
values(1, 100, 1);
insert into product_stock(product_id, qty, branch_id)
values(1, 50, 2);
insert into product_stock(product_id, qty, branch_id)
values(2, 80, 1);
我的查询:
SELECT IFNULL(SUM(s.qty),0) AS stock,
product_name
FROM product_stock s
RIGHT JOIN product p ON s.product_id=p.product_id
WHERE branch_id=1
GROUP BY product_name
ORDER BY product_name;
回报:
+-------+-------------------------------+
| stock | product_name |
+-------+-------------------------------+
| 100 | Apsana White DX Pencil |
| 80 | Diamond Glass Marking Pencil |
+-------+-------------------------------+
1 row in set (0.00 sec)
但我想有以下结果:
+-------+------------------------------+
| stock | product_name |
+-------+------------------------------+
| 0 | Apsana Black Pencil |
| 100 | Apsana White DX Pencil |
| 80 | Diamond Glass Marking Pencil |
+-------+------------------------------+
为了得到这个结果我应该运行哪些mysql查询?
答
尝试:
SELECT IFNULL(SUM(s.qty),0) AS stock,
product_name
FROM product_stock s
RIGHT JOIN product p ON s.product_id=p.product_id AND branch_id=1
GROUP BY product_name
ORDER BY product_name;
您当前的查询筛选出来的产品不匹配product_stock在WHERE子句中,有效地将外连接返回到内连接。
+0
非常感谢它是最好的解决方案。再次感谢。 – Tareq 2009-10-07 09:12:50
尝试使用左连接! – halocursed 2009-10-07 09:08:36
@Tareq这里看起来和你之前的问题非常相似:http://stackoverflow.com/questions/1530021/query-returns-too-few-rows – 2009-10-07 09:08:50
朋友,尽管它很相似,但结果却不同。如果我编辑以前的问题,我无法得到答案。所以,我必须添加另一个。谢谢。 – Tareq 2009-10-07 09:10:46