1
在我的數據庫中運行以下查詢時,我得到1077作爲輸出。Postgres「NOT IN」操作符用法
select count(distinct a_t1) from t1;
然後,當我運行此查詢,我得到459
select count(distinct a_t1) from t1
where a_t1 in (select a_t1 from t1 join t2 using (a_t1_t2) where a_t2=0);
上面是一樣的,這個查詢這也給459:
select count(distinct a_t1) from t1 join t2 using (a_t1_t2) where a_t2=0
但是,當我運行此查詢,我得到0而不是我期待的618:
select count(distinct a_t1) from t1
where a_t1 not in (select a_t1 from t1 join t2 using (a_t1_t2) where a_t2=0);
我正在運行PostgreSQL 9.1.5,這可能不是必需的。請在上面的查詢中指出我的錯誤。
UPDATE 1: 我創建了一個新表並將上述子查詢的結果輸出到該表中。然後,我跑了幾個查詢:
select count(distinct a_t1) from t1
where a_t1 not in (select a_t1 from sub_query_table order by a_t1 limit 10);
And Hooray!現在我得到10個答案!我能夠將限制增加到450.之後,我又開始變得0了。
更新2:
的sub_query_table中有459個值。最後,這個查詢給了我所需答案:
select count(distinct a_t1) from t1
where a_t1 not in (select a_t1 from sub_query_table order by a_t1 limit 459);
在哪裏,因爲這一個,給0作爲答案:
select count(distinct a_t1) from t1
where a_t1 not in (select a_t1 from sub_query_table);
但是,爲什麼會出現這種情況?
確實如此,但只佔a_t1的1個值,還有617個其他a_t1值,在我上次查詢的結果中沒有看到。 – Phani
@Phani有可能明顯減少計數?在所有條目中選擇相同的值? – OkieOth
我不確定我是否按照你說的去做。第一個查詢顯示有1077個不同的a_t1值。然後,第二個查詢顯示1077個值中有459個不同的值出現在子查詢的結果中。所以,應該有618個不同的a_t1值在子查詢的結果中不存在。但最後一個查詢返回0,如果我用'OR a_t1 = 0'更新它,我得到1作爲結果。 – Phani