【转】《与MySQL的零距离接触》第五章:子查询与连接 (5-4:由[NOT] IN/EXISTS引发的子查询)

5-4:由[NOT] IN/EXISTS引发的子查询

一. [NOT] IN

除了上一节我们讲到的子查询外,还有另一种子查询:[NOT] IN的子查询,语法结构为:

operand comparison_operator[NOT] IN(subquery)

=ANY 运算符与IN等效

!= ALL 或ALL运算符与NOT IN等效

以=ANY举例:

mysql> SELECT goods_id,goods_name,goods_price FROM tdb_goods WHERE goods_price = ANY(SELECT goods_price FROM tdb_goods WHERE goods_cate ='超级本');
+----------+---------------------------------+-------------+
| goods_id | goods_name                      | goods_price |
+----------+---------------------------------+-------------+
|        5 | X240(20ALA0EYCD) 12.5英寸超极本        |    4999.000 |
|        6 | U330P 13.3英寸超极本                   |    4299.000 |
|        7 | SVP13226SCB 13.3英寸触控超极本            |    7999.000 |
+----------+---------------------------------+-------------+
3 rows in set (0.00 sec)

mysql> SELECT goods_id,goods_name,goods_price FROM tdb_goods WHERE goods_price IN (SELECT goods_price FROM tdb_goods WHERE goods_cate ='超级本');
+----------+---------------------------------+-------------+
| goods_id | goods_name                      | goods_price |
+----------+---------------------------------+-------------+
|        5 | X240(20ALA0EYCD) 12.5英寸超极本        |    4999.000 |
|        6 | U330P 13.3英寸超极本                   |    4299.000 |
|        7 | SVP13226SCB 13.3英寸触控超极本            |    7999.000 |
+----------+---------------------------------+-------------+
3 rows in set (0.00 sec)

可以看到,=ANY 运算符与IN等效,结果都是一样的

二. [NOT] EXISTS

除了前面提到的两个子查询外,还有一个极少用到的子查询:[NOT] EXISTS

如果子查询返回任何行,EXISTS将返回TRUE;否则为FALSE

你可能感兴趣的:(【转】《与MySQL的零距离接触》第五章:子查询与连接 (5-4:由[NOT] IN/EXISTS引发的子查询))