为什么查询返回没有LIMIT子句的空结果集?

时间:2019-04-25 19:05:23

标签: mysql sql

我有这个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

它返回一个空结果集:

enter image description here

当我在limit 60之后添加group BY t.NAME子句时,它将返回预期结果:

enter image description here

为什么呢?

注意: limit 61或以上也不会导致任何结果。结果为limit 60以下。

1 个答案:

答案 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;