Mysql如果空结果返回默认值

时间:2014-06-07 07:05:10

标签: mysql

如果初始条目不存在,我试图让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返回一个空结果集(即零行)。 (查询了   0.0004秒)

我应该(如果我理解的话)获取我在IFNULL语句中设置的默认值。

那么如何才能正确地完成返回默认结果?

1 个答案:

答案 0 :(得分:1)

由于您正在使用评论表的agency_id进行过滤,因此我认为您需要正确的加入。

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