问题
I have a problem where I'm trying to calculate a sum of values per given id. I decided to do this using sub-queries (typically I'd use a join, but I'm also keeping a counter for each sub-query for clipping purposes - see this question for more info). For the sake of this question, assume I have the following MySQL query:
/* 1. */ SELECT
/* 2. */ t1.experiement_id,
/* 3. */ (SELECT sum(x.size)
/* 4. */ FROM (SELECT size, ( @rownum := @rownum + 1 ) AS `rownum`
/* 5. */ FROM data AS t0
/* 6. */ JOIN ( select @rownum := 0 )
/* 7. */ WHERE t0.experiment_id = t1.experiment_id
/* 8. */ ORDER BY size) AS x
/* 9. */ WHERE x.rownum <= t2.clip_index ) AS `sum`
/* 10. */
/* 11. */ FROM data AS t1
/* 12. */ JOIN data_clip AS t2 USING (experiment_id)
/* 13. */
/* 14. */ GROUP BY t1.experiment_id
The problem happens on row 7
, where I'm trying to isolate the rows in the sub-query that matches experiement_id
- I'm getting an error that t1.experiement_id
is an unknown column. This only happens on a query that's nested more than 1 level deep. Just as a check, I've noticed that t2.clip_index
is being processed fine. If I comment out row #7, the query returns fine (albeit with wrong results). Any idea how to make the sub-query recognize the parent table's column to use in my condition? Thanks.
回答1:
Have you tried something like this for counting rows instead of the user-defined variable ?
(SELECT sum(size) FROM data AS t0
WHERE t0.experiment_id = t1.experiment_id
ORDER BY size HAVING COUNT(*)<=t2.clip_index
) AS `sum`
Let me know if this works, it is an interesting issue we are examining here.
来源:https://stackoverflow.com/questions/7088107/how-to-get-a-nested-sub-query-to-recognize-parent-query-column