mysql中exists注意點
阿新 • • 發佈:2018-11-20
執行sql:
select 1 from dual where exists (select 0);
Query OK, 0 rows affected (0.44 sec)
mysql> insert into t3 values(1,'20160812');
Empty set (0.15 sec)
mysql> select 1 from dual where exists (select max(id) from t3 where id=2);
+---+
| 1 |
+---+
mysql> select 1 from dual where exists (select count(id) from t3 where id=2);
+---+
| 1 |
+---+
| 1 |
mysql> select id from t3 where id=2;
+---+
| NULL |
+---+
+---+
| 0 |
+---+
| 0 |
select 1 from dual where exists (select 0);
select 1 from dual where exists (select null);
執行結果都是1;
Query OK, 0 rows affected (0.44 sec)
mysql> insert into t3 values(1,'20160812');
Query OK, 1 row affected (0.16 sec)
mysql> select 1 from dual where exists (select id from t3 where id=2);Empty set (0.15 sec)
mysql> select 1 from dual where exists (select max(id) from t3 where id=2);
+---+
| 1 |
+---+
| 1 |
+---+
| 1 |
+---+
| 1 |
mysql> select id from t3 where id=2;
Empty set (0.15 sec)
mysql> select max(id) from t3 where id=2+---+
| NULL |
+---+
| NULL|
mysql> select count(id) from t3 where id=2+---+
| 0 |
+---+
| 0 |
由此可見:exists裡子查詢執行結果是null或者0,只要有一行結果,則exist就生效執行出結果,只有子查詢執行結果是Empty的時候exists才會過濾資料。