如果初始条目不存在,我试图让 mysql 返回一组基本值。
这是我尝试过的:
SELECT
IFNULL(count( mcr.rating ), 1) as rating_count,
IFNULL(avg( mcr.rating ), 5) as rating_average,
IFNULL(sum( mcr.rating ), 5) as rating_value,
IFNULL(mck.slug, '-') as rating_slug,
IFNULL(mck.name, '-') as rating_name,
IFNULL(mck.criteria_id, '-') as id,
IFNULL(mck.category, '-') as category
FROM microstock_criteria_key AS mck
LEFT JOIN microstock_collective_reviews AS mcr ON mck.criteria_id = mcr.criteria_id
WHERE mcr.agency_id =5
GROUP BY mck.criteria_id
ORDER BY mck.priority ASC
但我仍然得到:
MySQL returned an empty result set (i.e. zero rows). (Query took 0.0004 sec)
当我应该(如果我理解的话)获得我在 IFNULL
语句中设置的默认值时。
那么如何正确完成此操作以在可能为空的结果上返回默认结果?
最佳答案
由于您使用评论表的 Agency_id 进行过滤,因此我认为您需要 RIGHT JOIN。
SELECT
IFNULL(count( mcr.rating ), 1) as rating_count,
IFNULL(avg( mcr.rating ), 5) as rating_average,
IFNULL(sum( mcr.rating ), 5) as rating_value,
IFNULL(mck.slug, '-') as rating_slug,
IFNULL(mck.name, '-') as rating_name,
IFNULL(mck.criteria_id, '-') as id,
IFNULL(mck.category, '-') as category
FROM microstock_criteria_key AS mck
RIGHT JOIN microstock_collective_reviews AS mcr ON mck.criteria_id = mcr.criteria_id
WHERE mcr.agency_id =5
GROUP BY mck.criteria_id
ORDER BY mck.priority ASC
关于Mysql如果结果为空返回默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24094706/