sql left join无法得到正确的结果

时间:2012-09-11 08:31:26

标签: sql join where

现在,我有两个表,Locationq_Location,位置为主表。我写这样的sql左连接:

SQL1:
    SELECT L.ID,QL.* 
    FROM LOCATION L 
    LEFT JOIN Q_LOCATION QL ON L.ID=QL.LOCATION_ID 
                         AND L.WAREHOUSE_ID=QL.WAREHOUSE_ID
                         AND ISNULL(ql.VIRTUAL, 'N') = 'N' 
                         AND ISNULL(ql.PICKABLE, 'y') = 'Y' 
    where l.warehouse_id='mmc-main

但结果是错误的。如果是这样的sql语句:

SQL2:  
    SELECT L.ID,QL.* 
    FROM LOCATION L 
    LEFT JOIN Q_LOCATION QL ON L.ID=QL.LOCATION_ID 
                            AND L.WAREHOUSE_ID=QL.WAREHOUSE_ID
    where l.warehouse_id='mmc-main' 
    AND ISNULL(ql.VIRTUAL, 'N') = 'N'
    AND   ISNULL(ql.PICKABLE, 'y') = 'Y' 

现在结果如果正确的话。我想知道为什么第一个sql出错了,有人可以帮帮我吗?先谢谢!

1 个答案:

答案 0 :(得分:3)

小心在OUTER JOIN(左或右)中应用过滤器 - 它与在WHERE子句中应用过滤器不同。您的第一个查询无法按预期工作,因为如果连接失败,将仍会返回LEFT表行,并且将忽略您的其他RIGHT表过滤器ISNULL(ql.VIRTUAL, 'N') = 'N'ISNULL(ql.PICKABLE, 'y') = 'Y'。< / p>

另见:WHERE Clause vs ON when using JOIN