mysql。左连接计数不起作用

标签 mysql

我有两张 table 。 takeoffheaders 顾名思义是标题表,takeoffitems 是项目表。

某些标题记录没有任何相关项目记录。我需要获取相关项目记录的计数。

当我运行此代码时,我得到 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 

正如预期的那样,没有什么区别。

编辑。

当我删除其中一条不包含任何项目的 header 记录时,我仍然只取回 8 条记录,并且得到一条不同的零记录。

编辑2。

我在连接中只取回 8 条记录,但我只得到一条计数为零的记录....

编辑3

这是各个查询返回的记录

enter image description here 由于数据库发生变化,现在只有 21 条记录

enter image description here

最佳答案

分组依据位于不在选择范围内的表格上(至少一个未聚合的表格)

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

关于mysql。左连接计数不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45170409/

相关文章:

php - 从数组中获取值

javascript - 登录表单不与 MySQL 交互

java - 使用MyBatis在Java中执行Filename.sql文件

java - 返回的 JSONObject 始终为 null

mysql - 无法使用 gem mysql2 重新连接到 mysql 数据库

mysql - 如何提高 mysql 连接查询速度?

mysql - 有没有办法根据子查询的结果获取结果?

mysql - mysql 大页面选项的问题

mysql - 需要从 hive 中的给定时间戳中减去一些小时

mysql - postgresql查询到mysql