引用join / subselect中的上一个表

时间:2014-01-02 09:31:49

标签: mysql

我在编写复杂查询时通常非常聪明,但有时我会陷入这样简单的事情:

SELECT * FROM
orders o
JOIN (
    SELECT i.order_id, COUNT(*) AS order_item_count
    FROM order_item i WHERE i.order_id = o.order_id
) x
ON x.order_id = o.order_id
  

#1054 - Unknown column 'o.order_id' in 'where clause'

如何在subselect中引用order_id?

想要做的事情:

SELECT * FROM
orders o
JOIN order_item i WHERE i.order_id = o.order_id
ON i.order_id = o.order_id
GROUP BY o.order_id

我有多个表要加入,我希望order_id不要放在GROUP BY中。

1 个答案:

答案 0 :(得分:1)

抱歉,我的问题与How to specify the parent query field from within a subquery in mySQL?

重复

所以它的解决方案是将子选择放在字段区域而不是加入子数据集:

SELECT
   *,
   (SELECT COUNT(i.order_id)
    FROM order_item i
    WHERE i.order_id = o.order_id) AS order_item_count
FROM orders o