SQL按包含另一个表中字符串出现的帖子排序

时间:2012-01-19 22:04:04

标签: sql sql-server asp-classic

所以我有一个标签关键字表。

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

请帮忙!我知道有一些神秘的UNIONGROUP BY我在这里失踪。

2 个答案:

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