2017-07-18 78 views
0

我有2張桌子。 takeoffheaders正如其名稱所示,標題表和takeoffitems是項目表。Mysql。左計數不起作用

某些標頭記錄沒有任何相關的項目記錄。我需要計算相關項目記錄。

當我運行這段代碼時,我得到了23條記錄。

SELECT 
     takeoffheaders.Estimate_description 
    FROM 
     takeoffheaders 
    WHERE 
     TakeOffHeaders.CostCodeguid = '{026F8AEE-0ADA-4DD0-8826-0B0C3BDB15EC}' 
     and takeoffheaders.Job_Guid = '{FECD00C7-8C16-4D49-AC6A-DE5D5698219A}' 

當我運行這段代碼時,我只得到8條記錄。

Select 
    takeoffheaders.Estimate_description, 
    count(takeoffitems.Estimate_guid) AS COUNT 
FROM 
    takeoffheaders 
    LEFT JOIN takeoffitems 
    ON takeoffheaders.Estimate_guid = takeoffitems.Estimate_guid 
    AND takeoffheaders.Client_Guid = takeoffitems.Client_Guid 
WHERE 
    TakeOffHeaders.CostCodeguid = '{026F8AEE-0ADA-4DD0-8826-0B0C3BDB15EC}' 
and takeoffheaders.Job_Guid = '{FECD00C7-8C16-4D49-AC6A-DE5D5698219A}' 
GROUP BY 
    takeoffitems.Estimate_guid 

除了加入和計數它們是相同的。如果我改變

count(takeoffitems.Estimate_guid) AS COUNT 

to 

takeoffitems.Estimate_guid 

它和預期沒有什麼區別。

編輯。

當我刪除沒有任何項目的標題記錄之一時,我仍然只返回8條記錄,並且我得到一個不同的零記錄。

編輯2.

我只拿回8條記錄中加入,但我只得到一個零計數的一個記錄....

編輯被返回的記錄3

這裏由各自的querys

enter image description here 現在只有21條記錄由於DB

變化

+0

移動'TakeOffHeaders.CostCodeguid = '{026F8AEE-0ADA-4DD0-8826-0B0C3BDB15EC}' 和takeoffheaders.Job_Guid ='{FECD00C7-8C16-4D49-AC6A-DE5D5698219A}''到您的JOIN條件,而不是WHERE。 – fg78nc

+0

@ fg78nc這隻會改變沒有項目的標題記錄中的哪一個回來。仍然只有8條記錄。 – BrownPony

+0

你期望有多少? – fg78nc

回答

1

組由在表上沒有在選擇(至少一個,這不是聚集的)

SELECT takeoffheaders.Estimate_description 
    , count(takeoffitems.Estimate_guid) AS COUNT 
FROM takeoffheaders 
LEFT JOIN takeoffitems 
    ON takeoffheaders.Estimate_guid = takeoffitems.Estimate_guid 
AND takeoffheaders.Client_Guid = takeoffitems.Client_Guid 
WHERE TakeOffHeaders.CostCodeguid = '{026F8AEE-0ADA-4DD0-8826-0B0C3BDB15EC}' 
    and Takeoffheaders.Job_Guid = '{FECD00C7-8C16-4D49-AC6A-DE5D5698219A}' 
GROUP BY --takeoffitems.Estimate_guid --not this one 
     takeoffheaders.Estimate_guid --this one 
+0

仍然只返回8條記錄。對於空任務2是0,14,14。左 – BrownPony

+0

剛注意到你的小組在錯誤的桌子上。應該與select中的表相同。 – xQbert

+0

這就是它的xQbert。謝謝。 – BrownPony