我有这个mysql函数:
BEGIN
DECLARE top_tags VARCHAR(100) charset utf8;
SELECT substring_index(group_concat(x.NAME order BY x.tag_score DESC separator ','), ',', 5)
INTO top_tags
FROM (SELECT t.NAME, Sum(r.score) AS tag_score
FROM reputations r
JOIN qanda_tags qt ON qt.qanda_id = r.question_id
JOIN tags t ON t.id = qt.tag_id
WHERE r.owner_id = 1
AND r.date_time > CASE 'all'
WHEN 'WEEK' THEN unix_timestamp(date_sub(Now(), interval 1 week))
WHEN 'MONTH' THEN unix_timestamp(date_sub(now(), interval 1 month))
WHEN 'YEAR' THEN unix_timestamp(date_sub(now(), interval 1 year))
ELSE 1
END
group BY t.NAME ) x;
return top_tags;
end
它返回一个空结果集:
当我在limit 60
之后添加group BY t.NAME
子句时,它将返回预期结果:
为什么呢?
注意: limit 61
或以上也不会导致任何结果。结果为limit 60
以下。
答案 0 :(得分:1)
我不确定,但是在group_concat()
之前 进行过滤会更有效吗?
SELECT group_concat(x.NAME order BY x.tag_score DESC separator ',')
INTO top_tags
FROM (SELECT t.NAME, Sum(r.score) AS tag_score
FROM reputations r JOIN
qanda_tags qt
ON qt.qanda_id = r.question_id JOIN
tags t
ON t.id = qt.tag_id
WHERE r.owner_id = 1 AND
r.date_time > (CASE 'all'
WHEN 'WEEK' THEN unix_timestamp(date_sub(Now(), interval 1 week))
WHEN 'MONTH' THEN unix_timestamp(date_sub(now(), interval 1 month))
WHEN 'YEAR' THEN unix_timestamp(date_sub(now(), interval 1 year))
ELSE 1
END)
group BY t.NAME
order by tag_score desc
limit 5
) x;