在MySQL中,可以使用 EXISTS 和 NOT EXISTS 关键字来判断子查询是否返回任何行。
使用 EXISTS 关键字:
SELECT column1, column2
FROM table1
WHERE EXISTS (
SELECT *
FROM table2
WHERE table1.column = table2.column
);
上面的查询将返回 table1 表中满足条件的行,条件是 table2 中存在与 table1 中的列匹配的行。
使用 NOT EXISTS 关键字:
SELECT column1, column2
FROM table1
WHERE NOT EXISTS (
SELECT *
FROM table2
WHERE table1.column = table2.column
);
上面的查询将返回 table1 表中满足条件的行,条件是 table2 中不存在与 table1 中的列匹配的行。
辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读: mysql中having的作用是什么