Search code examples
mysqlsqlcoalesce

Null Column despite using Coalesce


Here is my Query:

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}';

I keep getting this error:

#1048 - Column 'item_id' cannot be null  

That line pertains to the sub-query from table reviews. I am using Coalesce; why does it still say its null?


Solution

  • I think this should work:

    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}'