只有子查詢返回的結果列包含一個值時,比較運算符才適用。假如一個子查詢返回的結果集是值的列表,這時比較運算符就必須用IN運算符代替。
IN運算符能夠檢測結果集中是否存在某個特定的值,若是檢測成功就執行外部的查詢。ide
查看在infos表中score字段內容符合條件對應的info表信息
SELECT * from info where score in (SELECT score FROM infos );3d
查詢結果:blog
查看在infos表和info表同名人信息
SELECT * from info where name in (SELECT name FROM infos );it
查詢結果:class
子查詢能夠使用比較運算符。這些比較運算符包括=、!=、>、>=、<、<=等。比較運算符在子查詢時使用的很是普遍。im
SELECT * from info where age >= (SELECT age FROM infos where id =4);d3
查詢結果:查詢
使用EXISTS關鍵字時,內層查詢語句不返回查詢的記錄。而是返回一個真假值。若是內層查詢語句查詢到知足條件的記錄,就返回一個真值(true),不然,將返回一個假值(false)。當返回的值爲true時,外層查詢語句將進行查詢;當返回的爲false時,外層查詢語句不進行查詢或者查詢不出任何記錄。db
SELECT * from info where exists (SELECT * from infos where id =2);img
查詢結果:
SELECT * from info where exists (SELECT * from infos where id =27);
查詢結果:
ANY關鍵字表示知足其中任意一個條件。使用ANY關鍵字時,只要知足內層查詢語句返回的結果中的任意一個,就能夠經過該條件來執行外層查詢語句。
SELECT * from info where age > ANY(SELECT age from infos);
查詢結果:
ALL關鍵字表示知足全部條件。使用ALL關鍵字時,只有知足內層查詢語句返回的全部結果,才能夠執行外層查詢語句。
SELECT * from info where age < all(SELECT age from infos);
查詢結果:
合併查詢結果是將多個SELECT語句的查詢結果合併到一塊兒。合併查詢結果使用UNION和UNION ALL關鍵字。
SELECT score from info UNION SELECT score from infos;
查詢結果:
SELECT score from info UNION SELECT name from infos;
查詢結果: