Subqueries with ANY or SOME

语法描述

由于列子查询返回的结果集是多行一列,因此不能直接使用(=,>,<,>=,<=,<>)这些比较操作符。在列子查询中可以使用 ANYSOME 操作符与比较操作符联合使用:

  • ANY:与比较操作符联合使用,表示与子查询返回的任何值比较为 TRUE,则返回结果为 true
  • SOMEANY 的别名,与 ANY 意义相同,但较少使用。

语法结构

  1. > SELECT column_name(s) FROM table_name WHERE column_name ANY (subquery);

示例

  1. create table t1 (a int);
  2. create table t2 (a int, b int);
  3. create table t3 (a int);
  4. create table t4 (a int not null, b int not null);
  5. create table t5 (a int);
  6. create table t6 (a int, b int);
  7. insert into t1 values (2);
  8. insert into t2 values (1,7),(2,7);
  9. insert into t4 values (4,8),(3,8),(5,9);
  10. insert into t5 values (null);
  11. insert into t3 values (6),(7),(3);
  12. insert into t6 values (10,7),(null,7);
  13. mysql> select * from t3 where a <> any (select b from t2);
  14. +------+
  15. | a |
  16. +------+
  17. | 6 |
  18. | 3 |
  19. +------+
  20. 2 rows in set (0.00 sec)
  21. mysql> select * from t3 where a <> some (select b from t2);
  22. +------+
  23. | a |
  24. +------+
  25. | 6 |
  26. | 3 |
  27. +------+
  28. 2 rows in set (0.00 sec)
  29. mysql> select * from t3 where a = some (select b from t2);
  30. +------+
  31. | a |
  32. +------+
  33. | 7 |
  34. +------+
  35. 1 row in set (0.00 sec)
  36. mysql> select * from t3 where a = any (select b from t2);
  37. +------+
  38. | a |
  39. +------+
  40. | 7 |
  41. +------+
  42. 1 row in set (0.00 sec)
  43. mysql> select a,b from t6 where a > any ( select a ,b from t4 where a>3);
  44. ERROR 1105 (HY000): subquery should return 1 column