引用嵌套子查询中的表

时间:2014-04-03 09:05:26

标签: mysql sql subquery where-clause

如何在"最外层"中引用ID_comp字段? WHERE子句中的表(别名为" cmp"):

SELECT
      (SELECT COUNT(*) cnt
       FROM 
           (SELECT trp.trip_no
        FROM Trip trp
        WHERE trp.ID_comp = cmp.ID_comp
        GROUP BY trp.trip_no) foo
      ) flights
FROM Company cmp

上面的代码给了我一个错误:"Unknown column 'cmp.ID_comp' in 'where clause'"

1 个答案:

答案 0 :(得分:0)

我认为你正在寻找这个:

SELECT 
   C.ID_comp,
   COUNT(T.ID_comp) trip_count
FROM company C
  LEFT JOIN Trip T
    ON C.ID_comp = T.ID_comp
GROUP BY C.ID_comp