如何在SQL中更快地运行此查询?

时间:2016-01-04 12:36:58

标签: sql

如何让此查询更快地运行:

SELECT *
FROM ( SELECT DISTINCT l.year,
              (select count(laws.id) from laws as laws WHERE laws.year = l.year  ) as count
      FROM laws as l
      ORDER BY l.year DESC
    ) s
WHERE count > 0

对于10000条记录,它运行大约23秒。

1 个答案:

答案 0 :(得分:3)

使用GROUP BY

select l.year, count(*)
from laws
group by l.year
order by l.year desc;

请注意,比较count > 0是多余的。这只会返回至少有一场比赛的年份。

我很好奇你如何提出你的查询,这比简单的聚合要复杂得多。