2015-05-12 67 views
2
mysql> show columns in m like 'fld'; 
+-------+-------------+------+-----+---------+-------+ 
| Field | Type  | Null | Key | Default | Extra | 
+-------+-------------+------+-----+---------+-------+ 
| fld | varchar(45) | YES | MUL | NULL |  | 
+-------+-------------+------+-----+---------+-------+ 
1 row in set (0.02 sec) 

mysql> show columns in i like 'fld'; 
+-------+-------------+------+-----+---------+-------+ 
| Field | Type  | Null | Key | Default | Extra | 
+-------+-------------+------+-----+---------+-------+ 
| fld | varchar(45) | YES | MUL | NULL |  | 
+-------+-------------+------+-----+---------+-------+ 
1 row in set (0.02 sec) 

mysql> select count(distinct fld) from i; 
+---------------------+ 
| count(distinct fld) | 
+---------------------+ 
|    27988 | 
+---------------------+ 
1 row in set (0.03 sec) 

mysql> select count(distinct fld) from m; 
+---------------------+ 
| count(distinct fld) | 
+---------------------+ 
|    72558 | 
+---------------------+ 
1 row in set (0.07 sec) 

根據我所瞭解的表格,上述結果看起來是合理的。爲什麼0結果在「哪裏不在」查詢

mysql> select count(*) from m where fld not in (select fld from i); 
+----------+ 
| count(*) | 
+----------+ 
|  0 | 
+----------+ 
1 row in set (0.11 sec) 

最後的結果似乎不合理。 There must be部分mfld不在i!有人可以解釋爲什麼我得到0作爲結果?


爲了完整(因爲我懷疑這可能是相關的),我也會貼上這樣的結果:

mysql> select count(*) from m where fld is null; 
+----------+ 
| count(*) | 
+----------+ 
|  0 | 
+----------+ 
1 row in set (0.00 sec) 

編輯:在答覆意見,我編輯在下面的信息也是,在情況下,它可以幫助別人回答我的問題:

  • select count(*) from m join i using (fld)產量9350;與left join,73087;與right join,28872.
  • select count(*) from i where fld is null產生810

回答

1

現在我已經想通了。 The documentation寫着:

爲符合SQL標準,IN回報NULL不僅如果在左側的表達式是NULL,而且如果不匹配,在列表中找到並在列表中的表現之一是NULL

因此,fld not in(即not fld in)返回not null(即null)只要有派生表null(這是這裏有)和fld未在派生表中發現(這是什麼我測試)。


可能有比這更好的解決辦法,但我使用(select fld from i where fld is not null)

+0

是的。奇怪的行爲。也許這有一個很好的理由,但到目前爲止,我只看到由於這個錯誤,並沒有優勢。順便說一下,這不僅僅在MySQL中。 – GolezTrol