where與group by同時存在時數據差異原因分析

where和group by同時使用是出現數據差異具體如下:

我們使用where 判斷 .financingProductId = ‘11111111111111111’
其中部分有同一個enterpriseInfoId有不同的的數據,不同的financingProductId (點題)
兩種實現方式

一、在where和group by同時使用來查詢數據

SELECT 
c.enterpriseInfoId,c.financingProductId
FROM 
c_cooperative_organization c 
WHERE 
  c.financingProductId = '11111111111111111'
GROUP BY c.enterpriseInfoId

二、group by得到的結果集作爲再進行where判斷

SELECT *  FROM(
SELECT 
c.enterpriseInfoId,c.financingProductId
FROM 
c_cooperative_organization c 

GROUP BY c.enterpriseInfoId
) d where d.financingProductId = '11111111111111111';

結論:第一種方式的結果會比第二種方式大
等價於用having

SELECT 
c.enterpriseInfoId,c.financingProductId
FROM 
c_cooperative_organization c 
GROUP BY c.enterpriseInfoId HAVING financingProductId = '11111111111111111'

分析

我們先看sql執行順序,

第一種方式的執行順序

先進行條件判斷再進行分組

第二種方式的執行順序

先進行分組再進行條件判斷

咋眼一看只是順序調換,如同乘除順序不會影響,其實不然

通過求數據集的差集來判斷有哪些數據數多出來的
where xxx in not(效率低,生成環境不建議使用)


SELECT b.enterpriseInfoId FROM (
SELECT 
c.enterpriseInfoId,c.financingProductId
FROM 
c_cooperative_organization c 
WHERE 
c.isOldVersion = '0'  and  c.financingProductId = '11111111111111111'
GROUP BY c.enterpriseInfoId
) b
where b.enterpriseInfoId not in
(SELECT d.enterpriseInfoId  FROM(
SELECT 
c.enterpriseInfoId,c.financingProductId
FROM 
c_cooperative_organization c 
WHERE 
c.isOldVersion = '0' 
GROUP BY c.enterpriseInfoId
) d where d.financingProductId = '11111111111111111'
)

得到4條
在這裏插入圖片描述
在看看其中一條的情況
在這裏插入圖片描述
出現瞭如上上點題的情況,不同的financingProductId (點題)

細細分析

第一種方式爲什麼多,是因爲在分組之前我們拿到了一條數據如下,再分組也有這數據了
在這裏插入圖片描述
第二種方式,它先分組,它取的可能就不是上面數據,可能是下面數據,這裏就少了這數據了。
在這裏插入圖片描述
所以造成了,數據差異。

建議使用Having

我們如果就是想查詢分組時,想要直接顯示某個值,該值通過參數傳進來。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章