用一條SQL查詢一張表中不一樣級別的字段(字段名稱相同)。 spa
需求:用一條SQL同時查出城市id、城市name、省份id和省份name。 ci
版本一以下
it
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
io
版本二 im
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
版本二查詢出來的結果
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
AND
tlOne.LOCATION_LEVEL = '2'
查詢出的結果同版本二同樣
別人寫的SQL版本一以下 img
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版本二以下 di
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
仔細觀察上述SQL會發現 vi
我寫的版本三和別人寫的版本一惟一的區別在於on後面的條件鏈接關鍵詞,我用的是ON,別人用的是where。這裏延伸出一個問題: co
left join on後面跟and和where的區別
1.on後面and 條件表示先過濾以後,再鏈接
2.on後面where條件表示先關聯以後,再過濾 至關內連了。。