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');
如下图所示:
注意事项
注意子查询的用法
注意子查询中各个关键字的区别
以上就是MySQL数据库中如何进行子查询的详细内容,更多请关注php中文网其它相关文章!
……