How to get a nested sub-query to recognize parent query column

房东的猫 提交于 2019-12-10 18:30:59

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!