2017-07-18 25 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