如何在MySQL数据库进行子查询

2024-12-26 22:46:23
推荐回答(1个)
回答1:

方法/步骤

1
首先,在一个查询中的查询结果作为外层查询的条件,可以用IN关键字,代码如下:
SELECT * FROM city WHERE CountryCode IN (SELECT Code FROM country);
如下图所示:

2
其次,外层查询的条件不在内层查询结果,可以用NOT IN关键字,代码如下:
SELECT * FROM city WHERE CountryCode NOT IN (SELECT Code FROM country);
如下图所示:

3
使用EXISTS关键字查询时,内层查询语句不返回查询的记录,而是返回一个Boolean值;当内层查询返回的值为true时,外层查询语句将进行查询,如果返回false时,将不进行查询或查询结果为空,代码如下:
SELECT * FROM city WHERE EXISTS (SELECT Name FROM country);
如下图所示:

4
由第三步可知,与EXISTS相对的是NOT EXISTS,当内层查询返回的值为false时,外层查询语句将进行查询,如果返回true时,将不进行查询或查询结果为空,代码如下:
SELECT * FROM city WHERE NOT EXISTS (SELECT Name FROM country);
如下图所示:

5
满足其中的任一条件,就可以通过该条件来执行外层查询语句,用关键字ANY,代码如下:
SELECT * FROM city WHERE Population >= ANY (SELECT Population FROM country);
如下图所示:

6
子查询还包含比较运算符,有“>="、“<="、"!="等关键字,代码如下:
SELECT * FROM city WHERE Population >= (SELECT Population FROM country WHERE Name = 'Afghanistan');
SELECT * FROM city WHERE Population <= (SELECT Population FROM country WHERE Name = 'Afghanistan');
SELECT * FROM city WHERE Population != (SELECT Population FROM country WHERE Name = 'Afghanistan');
如下图所示:

7
满足所有条件,只有满足内层查询语句返回所有结果,代码如下:
SELECT * FROM city WHERE Population >= ALL (SELECT Population FROM country WHERE Name = 'Afghanistan');
如下图所示:

http://jingyan.baidu.com/article/73c3ce280d68f2e50243d960.html