Getting the number of rows with a GROUP BY query within a subquery
I'm building a MySQL query with subqueries. The query requires, as described in Getting the number of rows with a GROUP BY query, the number of records returned by a group-by query, because I want the number of days with records in the database. So I'm using the following:
SELECT
COUNT(*)
FROM
(
SELECT
cvdbs2.dateDone
FROM
cvdbStatistics cvdbs2
WHERE
cvdbs2.mediatorId = 123
GROUP BY
DATE_FORMAT( cvdbs2.dateDone, "%Y-%d-%m" )
) AS activityTempTable
Now, I want this as a subquery, because I need some more data with different WHERE statements. So my query becomes:
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
(I left out some irrelevant WHERE-statements from my queries. 409 is just an example id, this is inserted by PHP).
Now, I'm getting the following error:
#1054 - Unknown column 'mediators.id' in 'where clause'
MySQL forgot about the mediators.id in the deepest subquery. How can I build a query, with the number of results of a GROUP-BY query, which requires a value from the main query, as one of the results? Why isn't the deepest query aware of 'me开发者_开发知识库diators.id'?
Try the following:
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
Did you try to put also the "mediators" table in the FROM of the deepest subquery ? Because they are two different queries and the tables of the first one are not called in the subquery. I'm not sure of what i say but i think the only relation between the query and the subquery is the result return by the subquery.
精彩评论