右连接查询不起作用

时间:2013-08-13 11:24:30

标签: mysql sql

我有两个表:opensalesorderitems

我想基于item_number从两个表中检索数据,并且它可以正常使用以下查询。 (使用INNER JOIN)

SELECT opensalesorder.so_number,items.VendorName,opensalesorder.item_number
FROM `opensalesorder` 
INNER JOIN items on opensalesorder.item_number = items.ItemName 
WHERE items.ItemType = 'Stock' and opensalesorder.status NOT LIKE 'on po' 
GROUP BY opensalesorder.item_number

但是我也想要'items'表中的所有行,即使找不到与opensalesorder和items中的ItemName匹配的内容。

但是使用以下查询似乎不适合我。

SELECT opensalesorder.so_number,items.VendorName,opensalesorder.item_number
FROM `opensalesorder` 
RIGHT JOIN items on opensalesorder.item_number = items.ItemName  
WHERE items.ItemType = 'Stock' and opensalesorder.status NOT LIKE 'on po' 
GROUP BY opensalesorder.item_number

右连接将返回右表中的结果,即使左侧没有找到匹配项。

查询是否正确?

由于

1 个答案:

答案 0 :(得分:8)

这是您的查询:

SELECT opensalesorder.so_number,items.VendorName,opensalesorder.item_number
FROM `opensalesorder` right join
     items
     on opensalesorder.item_number = items.ItemName  
 WHERE items.ItemType = 'Stock' and opensalesorder.status NOT LIKE 'on po'
 group by opensalesorder.item_number;

where上的opensalesorder条件是“撤消”right join。值NULL将导致其失败。

解决方案是将其移至on子句:

SELECT opensalesorder.so_number,items.VendorName,opensalesorder.item_number
FROM `opensalesorder` right join
     items
     on opensalesorder.item_number = items.ItemName and
        opensalesorder.status NOT LIKE 'on po'
 WHERE items.ItemType = 'Stock'
 group by opensalesorder.item_number;