SQL -- left join on and 與 left join on where的區別

最近作工程時,須要用一條SQL查詢一張表中不一樣級別的字段(字段名稱相同)。html

直接上例子吧sql

以下是地點表的部分截圖,圖1是全部的省份級別ui

                                圖1:全部的省份級別spa


                                    圖2:部分城市級別
需求:用一條SQL同時查出城市id、城市name、省份id和省份name。.net

我寫的SQL版本一以下unix

SELECT
    tlUp.LOCATION_ID as cityId,
    tlUp.LOCATION_NAME as cityName,
    tlDown.LOCATION_ID as provinceId,
    tlDown.LOCATION_NAME as provinceName
FROM
(SELECT
    tl.LOCATION_ID,
    tl.LOCATION_NAME,
    tl.SUPER_LOCATION_ID
FROM
    t_location tl) tlUp,t_location tlDown
WHERE
    tlUp.SUPER_LOCATION_ID = tlDown.LOCATION_ID

版本一查詢出的結果code


我寫的SQL版本二以下htm

SELECT
    tlOne.LOCATION_ID as cityId,
    tlOne.LOCATION_NAME as cityName,
    tlTwo.LOCATION_ID as provinceId,
    tlTwo.LOCATION_NAME as provinceName
FROM
    t_location tlOne
LEFT JOIN 
    t_location tlTwo 
ON
    tlOne.SUPER_LOCATION_ID = tlTwo.LOCATION_ID

版本二查詢出來的結果blog

我寫的SQL版本三ci

SELECT
    tlOne.LOCATION_ID as cityId,
    tlOne.LOCATION_NAME as cityName,
    tlTwo.LOCATION_ID as provinceId,
    tlTwo.LOCATION_NAME as provinceName
FROM
    t_location tlOne
LEFT JOIN 
    t_location tlTwo 
ON
    tlOne.SUPER_LOCATION_ID = tlTwo.LOCATION_ID
AND
    tlOne.LOCATION_LEVEL = '2'

查詢出的結果同版本二同樣

別人寫的SQL版本一以下

SELECT
    tlOne.LOCATION_ID as cityId,
    tlOne.LOCATION_NAME as cityName,
    tlTwo.LOCATION_ID as provinceId,
    tlTwo.LOCATION_NAME as provinceName
FROM
    t_location tlOne
LEFT JOIN 
    t_location tlTwo 
ON
    tlOne.SUPER_LOCATION_ID = tlTwo.LOCATION_ID
WHERE
    tlOne.LOCATION_LEVEL = '2'

查詢出的結果同版本一 同樣

別人寫的SQL版本二以下

SELECT
    tlUp.LOCATION_ID as cityId,
    tlUp.LOCATION_NAME as cityName,
    tlDown.LOCATION_ID as provinceId,
    tlDown.LOCATION_NAME as provinceName
FROM t_location tlUp,t_location tlDown
WHERE
    tlUp.SUPER_LOCATION_ID = tlDown.LOCATION_ID

查詢出的結果同版本一 一致


分析:

很明顯,我寫的版本1、別人寫的版本1、版本二是對的。

仔細觀察上述SQL會發現

我寫的版本三和別人寫的版本一惟一的區別在於on後面的條件鏈接關鍵詞,我用的是ON,別人用的是where。這裏延伸出一個問題:

left join on後面跟and和where的區別

閱讀以下文章

http://blog.csdn.net/nsj820/article/details/6001718

http://blog.csdn.net/xingfeng0501/article/details/7816703

http://blog.chinaunix.net/uid-26982899-id-3284820.html

在使用left jion時,on和where條件的區別以下:

1.on後面and 條件表示先過濾以後,再鏈接

因此個人SQL版本二與SQL版本三查出的結果是同樣的.

2.on後面where條件表示先關聯以後,再過濾

因此別人寫的SQL版本一是對的.

相關文章
相關標籤/搜索