查询子查询不返回应返回的值

时间:2017-09-29 06:05:29

标签: mysql sql correlated-subquery

为什么这个查询

SELECT *
FROM tbl X
WHERE NOT EXISTS (SELECT * FROM tbl Y WHERE X.end_date=Y.start_date)
ORDER BY accommodation_id, start_date

不会返回以下行?

enter image description here

我验证了在AND accommodation_id = 7049子句中添加WHERE的行未返回,因此生成的查询为:

SELECT * FROM wp_byt_accommodation_vacancies X WHERE NOT EXISTS(SELECT * FROM wp_byt_accommodation_vacancies Y WHERE X.end_date=Y.start_date) AND accommodation_id = 7049 ORDER BY accommodation_id, start_date

我使用以下查询验证了start_date = '2017-04-08没有accommodation_id行:

SELECT * FROM wp_byt_accommodation_vacancies WHERE accommodation_id = 7049 AND start_date = '2017-04-07'

1 个答案:

答案 0 :(得分:1)

您应该使用以下查询

SELECT *
FROM tbl X
WHERE NOT EXISTS (  SELECT * 
                    FROM tbl Y 
                    WHERE X.end_date=Y.start_date
                    AND X.accommodation_id = Y.accommodation_id)
ORDER BY accommodation_id, start_date

您忘记链接密钥X.accommodation_id = Y.accommodation_id