在子查询中获取具有GROUP BY查询的行数

时间:2011-09-22 09:26:31

标签: mysql sql group-by subquery

我正在使用子查询构建MySQL查询。如Getting the number of rows with a GROUP BY query中所述,查询要求分组查询返回的记录数,因为我想要数据库中记录的天数。所以我使用以下内容:

SELECT
  COUNT(*)
FROM
(
  SELECT
    cvdbs2.dateDone
  FROM
    cvdbStatistics cvdbs2
  WHERE
    cvdbs2.mediatorId = 123
  GROUP BY
    DATE_FORMAT( cvdbs2.dateDone, "%Y-%d-%m" )
) AS activityTempTable

现在,我希望将其作为子查询,因为我需要更多具有不同WHERE语句的数据。所以我的查询变为:

SELECT
  x,
  y, 
  z,
  (
    SELECT
      COUNT(*)
    FROM
    (
      SELECT
        cvdbs2.dateDone
      FROM
        cvdbStatistics cvdbs2
      WHERE
        cvdbs2.mediatorId = mediators.id
      GROUP BY
        DATE_FORMAT( cvdbs2.dateDone, "%Y-%d-%m" )
    ) AS activityTempTable
  ) AS activeDays
FROM
  mediators
LEFT JOIN
  cvdbStatistics
ON
  mediators.id = cvdbStatistics.mediatorId
WHERE
  mediators.recruiterId = 409
GROUP BY
  mediators.email

(我从查询中省略了一些不相关的WHERE语句.409只是一个示例id,这是由PHP插入的。)

现在,我收到以下错误:

#1054 - Unknown column 'mediators.id' in 'where clause' 

MySQL在最深的子查询中忘记了mediators.id。如何使用GROUP-BY查询的结果数量构建查询,该查询需要主查询中的值作为结果之一?为什么最深的查询不能识别'mediators.id'?

2 个答案:

答案 0 :(得分:1)

尝试以下方法:

SELECT
  x,
  y, 
  z,
  (
    SELECT
      COUNT(distinct DATE_FORMAT( cvdbs2.dateDone, "%Y-%d-%m" ))
    FROM
      cvdbStatistics cvdbs2
    WHERE
      cvdbs2.mediatorId = mediators.id
  ) AS activeDays
FROM
  mediators
LEFT JOIN
  cvdbStatistics
ON
  mediators.id = cvdbStatistics.mediatorId
WHERE
  mediators.recruiterId = 409
GROUP BY
  mediators.email

答案 1 :(得分:0)

您是否尝试将“调解员”表放在最深子查询的FROM中?因为它们是两个不同的查询,并且子查询中不调用第一个查询的表。我不确定我说的是什么,但我认为查询和子查询之间的唯一关系是子查询返回的结果。