简体   繁体   中英

sql left join cannot get right result

Now ,I have two tables, Location and q_Location , location as main table .I write sql left join like this:

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

but the result is wrong. if sql statement like this:

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' 

now The result if correct. I want to know why the first sql is wrong, somebody can help me ? thanks first!

Be careful about applying filters in an OUTER JOIN (left or right) - it is NOT the same as applying the filter in the WHERE clause. Your first query doesn't work as you expect it to, because if the join fails, the LEFT table rows will still be returned, and your additional RIGHT table filters ISNULL(ql.VIRTUAL, 'N') = 'N' and ISNULL(ql.PICKABLE, 'y') = 'Y' will be ignored.

See also here: WHERE Clause vs ON when using JOIN

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM