所以我有一个标签关键字表。
Tags
------------------
asp
sql
html
和一个充满帖子的表格
posts
------------------
I really like ASP
This week with stuff about ASP
This post contains SQL
我想按照帖子表中包含事件的大多数唯一帖子的顺序显示前10个标签。
这就是我所拥有的,但它是垃圾,我感到惭愧。
SELECT Tag,(SELECT Count(*) FROM Posts WHERE post LIKE '%Tags.Tag%') As Mentions FROM Tags ORDER BY Mentions DESC
请帮忙!我知道有一些神秘的UNION
或GROUP BY
我在这里失踪。
答案 0 :(得分:3)
SELECT TOP 10 *
FROM (
SELECT tag,COUNT(tag) AS Total
FROM tags t
JOIN posts p ON p.post LIKE '%' + t.tag + '%'
GROUP BY tags
) totals
ORDER BY Total Desc
答案 1 :(得分:0)
在MySQL中测试:
SELECT tag,count(*) AS n
FROM tags
JOIN posts ON post LIKE CONCAT("%",tag,"%")
GROUP BY tag
ORDER BY n DESC
LIMIT 10
为了说明这是如何工作的,在没有GROUP BY
的情况下首先运行是有益的SELECT tag,post
FROM tags
JOIN posts ON post LIKE CONCAT("%",tag,"%");
+------+------------------------+
| tag | post |
+------+------------------------+
| asp | I really like asp |
| asp | this week: asp |
| sql | this post contains sql |
+------+------------------------+
3 rows in set (0.00 sec)