MySQL:LEFT JOIN ..即使表2中没有,也从表1中选择全部?

时间:2009-10-21 18:50:27

标签: sql mysql left-join

我正在加入几张桌子进行选择

如果第2,第3,第4表中没有任何匹配,只要第一个表匹配,我仍然想要拉结果。我以为LEFT JOIN这样做了,但事实并非如此。

以下是完整查询:

SELECT cart_product.*, prod_drop_products.prod_drop_product_name, everlon_sheet.*, cart_product.product_id AS product_id 
FROM cart_product 
LEFT JOIN everlon_sheet ON cart_product.product_id = everlon_sheet.product_id 
LEFT JOIN prod_drop_products ON cart_product.product_id = prod_drop_products.product_id 
LEFT JOIN prod_drop ON prod_drop.prod_drop_id = prod_drop_products.prod_drop_id 
WHERE prod_drop.prod_drop_name = "Carat Weight" AND cart_product.product_brand = "everlon" 
ORDER BY cart_product.product_manufacturer_num

拉出316结果

以下是没有连接的查询:

SELECT cart_product.* 
FROM cart_product 
WHERE cart_product.product_brand = "everlon" 
ORDER BY cart_product.product_manufacturer_num

这会得到362个结果

由于我在JOIN qry中的 WHERE prod_drop.prod_drop_name =“Carat Weight”子句,我发生了预感。但是有没有办法在上面的查询中提取我需要的内容,但是仍然从第一个(最左边的,cart_product)表中提取所有内容,即使其他表中没有匹配项?

谢谢!

3 个答案:

答案 0 :(得分:3)

如果右侧没有匹配项,则prod_drop.prod_drop_name将为null

添加OR prod_drop.prod_drop_name IS NULL应解决您的问题。

答案 1 :(得分:1)

WHERE prod_drop.prod_drop_name = "Carat Weight" or prod_drop.prod_drop_name is null

答案 2 :(得分:1)

更改

WHERE prod_drop.prod_drop_name = "Carat Weight" AND cart_product.product_brand = "everlon" 

WHERE (prod_drop.prod_drop_name = "Carat Weight" OR prod_drop.prod_drop_name IS NULL) AND cart_product.product_brand = "everlon" 

如果prod_drop中没有匹配的值,查询现在也将返回匹配。