在第3级子查询中使用列

时间:2012-11-01 22:20:04

标签: mysql sql join subquery

如何在第3级子查询中使用顶级SELECT中的列?

我尝试了这个,但它给出了:unknown column foo.id

SELECT foo.id,
       (
           SELECT SUM(bar.amount)
           FROM bar
           JOIN (
               SELECT DISTINCT ding.id
               FROM baz
               JOIN ding ON ding.baz_id = baz.id
               WHERE baz.foo_id = foo.id
           ) AS j ON j.id = bar.id
       ) AS amount
FROM foo

1 个答案:

答案 0 :(得分:1)

尝试     SELECT foo_id

FROM (
       SELECT SUM(bar.amount),j.foo_id
       FROM bar
       JOIN (
           SELECT DISTINCT ding.id,baz.foo_id
           FROM baz
           JOIN ding ON ding.baz_id = baz.id
       ) AS j ON j.id = bar.id
   ) AS amount;