mysql - 空列尽管使用 Coalesce

标签 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;为什么它仍然说它为 null?

最佳答案

我认为这应该可行:

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

关于mysql - 空列尽管使用 Coalesce,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16368946/

相关文章:

mysql - 如何使用MySQL删除两个固定字符串之间的随机字符串?

mysql - 如何获取最新记录

php - SQL 检查当天

php - 如何获取所有记录,即使是那些没有匹配连接的记录 - MySQL

postgresql - 如何确保存储函数始终返回 TRUE 或 FALSE?

mysql - 合并 MySQL 中的整个记录

mysql - 将这个带有 HABTM 相关数据的巨大查询转换为 CakePHP 查找

sql - 在一个特定列上连接多个表

c# - NHibernate QueryOver 将一个属性合并到另一个属性

MySQL:如何选择最新日期在特定日期之前的记录