簡體   English   中英

select distinct count(id)vs select count(distinct id)

[英]select distinct count(id) vs select count(distinct id)

我正試圖從表中獲取不同的值。 當我select distinct count(id) from table運行select distinct count(id) from table我得到了超過一百萬的計數。 但是,如果我select count(distinct id) from table運行select count(distinct id) from table我只有大約300k計數。 這兩個查詢的區別是什么?

謝謝

當您select distinct count(id)您基本上在做:

select distinct cnt
from (select count(id) as cnt from t) t;

因為內部查詢只返回一行,所以distinct不執行任何操作。 查詢計算表中的行數 (更准確地說, id不為null的行數)。

另一方面,當你這樣做時:

select count(distinct id)
from t;

然后查詢計算id在表中所采用的不同值的數量。 這似乎是你想要的。

第二個選擇肯定是你想要的,因為它將聚合id(如果你有10個id = 5的記錄,那么它們將被計為一個記錄)並且select將返回“表中有多少個不同的id” 。 然而,第一個選擇將做一些奇怪的事情,我不完全確定它會做什么。

如果id是pk,則具有distinct count(id)將匹配返回的具有count(distinct id)的行的count(distinct id)

如果id不是pk但具有唯一約束(僅在id上,不與任何其他列組合),則返回帶有count(distinct id)的行的count(distinct id)將等於具有distinct count(id) ,如在pk的情況下。

如果id只是另一列, select count distinct count(id) from table將返回one row ,其中id列為NOT NULL的記錄,其中select count count(distinct id) from table將返回'one column'with表中的所有非NULL唯一ID。

在任何情況下,返回的計數或行數都不會超過表中行的總數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM