Mysql
SELECT icw a COUNT 和 INNER JOIN 在 WHERE 子句中使用字元串文字和數值時會給出不同的結果
我有一個 MySQL 查詢:
SELECT p.informationProvider as pGLN, p.productID, p.productStatus FROM tblproducts AS p WHERE -- informationProvider is of type varchar(14) p.informationProvider = '8718885110005'
結果是:
pGLN productID productStatus 8718885110005 497905 closed 8718885110005 497906 closed 8718885110005 497907 closed 8718885110005 497908 closed 8718885110005 505972 closed 8718885110005 505973 closed 8718885110005 508261 received 8718885110005 508262 received 8718885110005 508263 received 8718885110005 513591 received 8718885110005 517529 received 8718885110005 537381 received
現在我有另一個查詢:
SELECT c.informationProvider as cGLN, c.companyName FROM tblcompanies as c WHERE -- informationProvider is of type varchar(14) c.informationProvider = 8718885110005
結果是:
cGLN companyName 8718885110005 Oliva BV
現在我將結合這兩個查詢。
SELECT c.informationProvider as cGLN, p.informationProvider as pGLN, COUNT(p.productID) AS count, p.productID, p.productStatus FROM tblproducts AS p INNER JOIN tblcompanies AS c ON (c.informationProvider = p.informationProvider) WHERE p.productStatus IN ('requested' , 'expected', 'open') -- closed and received aren't in the list AND c.informationProvider = '8718885110005'
結果:
cGLN pGLN count productID productStatus 8718885110005 NULL 0 NULL NULL
- 問題 - - -
好的,我現在稍微改變一下。我將更
AND c.informationProvider = '8718885110005'
改為AND c.informationProvider = 8718885110005
. 因此,字元串將顯示為整數。結果是:
cGLN pGLN count productID productStatus NULL NULL 0 NULL NULL
這讓我很驚訝,為什麼 cGLN 單元格有 NULL?
我的第一個想法是檢查字元串值是否等於整數。令我驚訝的是,他們是。
SELECT 8718885110005 = '8718885110005'; -- this is 1
這更讓我吃驚。
我的問題:為什麼 cGLN 為 NULL?
評論者非常有幫助。他們促使我朝著正確的方向思考。讓我解釋。
如果你有這樣的表:
gln status 108 closed 108 open 108 closed
而且,您將執行如下查詢:
SELECT COUNT(gln) FROM tableA
結果將是
3
。如果您要執行如下查詢:
SELECT COUNT(gln), status FROM tableA
然後你只會看到 1 個狀態,其他狀態單元格會消失。這種失踪可能意味著麻煩。
正確的查詢應如下所示:
SELECT COUNT(gln), status FROM tableA GROUP BY status
ONLY_FULL_GROUP_BY
MySQL 可以在不同的模式下工作。其中一種模式稱為:
ONLY_FULL_GROUP_BY
. 此模式在某些數據庫伺服器上已關閉。此模式強制數據庫管理員GROUP BY
在聚合查詢(使用 a 的查詢COUNT()
)中使用 。連結:https ://dev.mysql.com/doc/refman/8.0/en/sql-mode.html#sqlmode_only_full_group_by
@danblack 的想法是正確的。查詢應如下所示:
SELECT c.informationProvider as cGLN, p.informationProvider as pGLN, COUNT(p.productID) AS count, p.productID, p.productStatus FROM tblproducts AS p INNER JOIN tblcompanies AS c ON (c.informationProvider = p.informationProvider) WHERE p.productStatus IN ('requested' , 'expected', 'open') AND c.informationProvider = '8718885110005' GROUP BY p.productID, p.productStatus, p.informationProvider