带LEFT JOIN的嵌套SELECT语句

时间:2012-10-19 08:23:59

标签: php mysql sql left-join

我不能为我的生活弄清楚这个SQL语句有什么问题以及为什么它没有产生任何结果。如果我取出LEFT JOIN是有效的,那么它有什么问题呢?

SELECT  b.id, r.avg_rating
FROM    items AS b
LEFT JOIN
(
    SELECT avg(rating) as avg_rating
    FROM ratings 
    GROUP BY item_id
) AS r 
  ON b.id = r.item_id
WHERE b.creator = " . $user_id . " 
AND b.active = 1
AND b.deleted = 0
ORDER BY b.order ASC, b.added DESC

非常感谢帮助。

1 个答案:

答案 0 :(得分:19)

在子查询中添加item_id列(我保证它可以正常工作),以便ON子句可以找到r.item_id

SELECT item_id, avg(rating) as avg_rating
FROM ratings 
GROUP BY item_id