尽管使用Coalesce,仍然是空列

时间:2013-05-03 23:24:06

标签: mysql sql coalesce

这是我的查询:

SELECT 
    i.item, 
    COALESCE(COUNT(r.item_id), 0) AS TotalRating, 
    SUM(r.rating) as RatingSum,  
    re.tR as TotalReview,
    AVG(r.rating) AS AverageRating
FROM items AS i
LEFT JOIN ratings AS r
    ON (r.item_id = i.item_id)
LEFT JOIN
    (SELECT item_id,COALESCE(COUNT(item_id),0) AS tR
    FROM reviews
    WHERE item_id = '{$itemId}') AS re
ON re.item_id = i.item_id  
WHERE i.item_id = '{$itemId}';

我一直收到这个错误:

#1048 - Column 'item_id' cannot be null  

该行与表reviews中的子查询有关。我正在使用Coalesce;为什么它仍然说它为空?

1 个答案:

答案 0 :(得分:3)

我认为这应该有效:

SELECT i.item,
       r.totalRating, COALESCE(r.ratingSum, 0), COALESCE(r.averageRating, 0),
       re.totalReview
FROM items i
JOIN (select COUNT(*) totalRating, SUM(rating) ratingSum, AVG(rating) averageRating
      FROM ratings
      WHERE item_id = '${item_id}') r
ON (1 = 1)
JOIN (select COUNT(*) totalReview
      FROM reviews
      WHERE item_id = '${item_id}') re
ON (1 = 1)
WHERE item_id = '${item_id}'