1. 程式人生 > >mysql中exists注意點

mysql中exists注意點

執行sql:
select 1 from dual where exists (select 0);

select 1 from dual where exists (select null);

執行結果都是1;


mysql> create table t3(id int,t datetime);
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 |

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;

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才會過濾資料。