我目前正在處理一個應該採取一些任意輸入數據,做一些自然語言處理,並動態生成相應的SQL查詢的項目。我還有一個「參考」SQL查詢集,我可以用它來比較我的SQL,以驗證SQL生成是否準確。SQL連接和嵌套查詢返回不同的記錄
這是我生成這樣一個SQL查詢:
SELECT DISTINCT t0.airline_code
FROM (
SELECT airline.*
FROM airline, flight
WHERE (
(airline.airline_code = flight.airline_code)
AND
(flight.flight_days = 'DAILY')
)
)
AS t0
INNER JOIN (
SELECT airline.*
FROM airline, flight, airport_service, city
WHERE (
(airline.airline_code = flight.airline_code)
AND
(flight.from_airport = airport_service.airport_code)
AND
(airport_service.city_code = city.city_code)
AND
(city.city_name = 'BOSTON')
)
)
AS t1
ON t0.airline_code = t1.airline_code
INNER JOIN (
SELECT airline.*
FROM airline, flight, airport_service, city
WHERE (
(airline.airline_code = flight.airline_code)
AND
(flight.to_airport = airport_service.airport_code)
AND
(airport_service.city_code = city.city_code)
AND
(city.city_name = 'DALLAS')
)
)
AS t2
ON t1.airline_code = t2.airline_code;
運行此返回以下列:
airline_code
------------
AA
CO
HP
TW
DL
NW
UA
US
參考SQL,然而,返回略有不同的結果:
SELECT DISTINCT airline.airline_code
FROM airline
WHERE airline.airline_code IN
(SELECT flight.airline_code
FROM flight
WHERE (flight.flight_days = 'DAILY'
AND (flight.from_airport IN
(SELECT airport_service.airport_code
FROM airport_service
WHERE airport_service.city_code IN
(SELECT city.city_code
FROM city
WHERE city.city_name = 'BOSTON'))
AND flight.to_airport IN
(SELECT airport_service.airport_code
FROM airport_service
WHERE airport_service.city_code IN
(SELECT city.city_code
FROM city
WHERE city.city_name = 'DALLAS')))));
結果:
airline_code
------------
AA
DL
TW
UA
US
顯然,兩者不同之處在於第一個使用連接,第二個使用嵌套SQL語句。但是,對於我正在使用的其他生成的SQL /參考SQL,這似乎沒有造成任何問題,它們的結構相似(生成的SQL使用連接,參考SQL嵌套)。我對SQL很陌生,幾乎完全不瞭解數據庫,所以我可能會錯過一些顯而易見的東西,但對於我而言,我看不出爲什麼兩條SQL語句返回不同的結果。他們似乎功能完全相同,盡我所知。有人知道我做錯了什麼,以及我如何修復生成的SQL來匹配參考?
如果它的事項,我使用Microsoft SQL Server 2012
我認爲第一個查詢將返回從波士頓到達拉斯的所有每日航班,第二個將返回從波士頓到達拉斯的所有每日航班。您應該添加AND t0.airline_code = t2.airline_code來首先查詢 – bksi
@bksi,這不完全正確,t0.airline_code因爲傳遞性已經與t2.airline_code相同。 –