这是我的问题:
SELECT * FROM (
SELECT count(*) cnt, * FROM articles_tag
GROUP BY tag_id
) x
ORDER BY cnt
LIMIT 2
但是它会在(
附近的第一行引发语法错误。我该如何解决?
我想选择最常用的2个最后一个标签。
// articles_tag
+----+------------+--------+
| id | article_id | tag_id |
+----+------------+--------+
| 1 | 123 | 4 |
| 2 | 456 | 3 |
| 3 | 789 | 6 |
| 4 | 123 | 3 |
| 5 | 456 | 6 |
| 6 | 987 | 2 |
+----+------------+--------+
预期结果:
+--------+
| tag_id |
+--------+
| 3 |
| 6 |
+--------+
答案 0 :(得分:2)
我认为你的意思是
select tag_id,count(*) as cnt from articles_tag group by tag_id order by count(*) limit 2
答案 1 :(得分:1)
您不需要子选择,只需计算出现次数,然后按顺序排序并将选择限制为2.
所以它会是:
SELECT tag_id, COUNT(tag_id) occurrences FROM articles_tag
GROUP BY tag_id
ORDER BY occurrences DESC
LIMIT 2