我正在寻找最好的方法来改善我的网站的搜索功能。
我有两个MySQL表“文章”和“标签”
->列在“文章”中
aid (auto increment)
headline
..and a few more标记中的->列(每个标签的新条目)
tid (auto increment)
aid (ID from 'articles')
tag例如,如果我有一篇标题为“这是一篇绿色文章”的文章,而这篇文章的标签是“蓝色”、“黄色”
还有一篇文章的标题是“这是另一个测试”,标题是“蓝色”、“黄色”、“粉红色”和“黑色”
如果访问者现在正在搜索“绿色粉红黑色”,mysql应该找到“这是一篇绿色文章”,还有另一篇文章,因为它的标签是“粉色”和“黑色”
此外,我需要一个功能,以排序的文章,根据其相关性。因此,在这个例子中,文章“这是另一个测试”应该首先显示,因为如果标签“粉红色”和“黑色”和“这是绿色的文章”位于第二位置(标题中只有“绿色”)
在最后几个小时里,我尝试了一些查询,比如match..against和joins,但是这对我来说太复杂了。
有人给我个提示吗?
(对不起,我的英语很差)
发布于 2012-08-29 21:06:13
您的查询应该如下所示:
SELECT
DISTINCT articles.aid
FROM articles
INNER JOIN tags
ON articles.aid = tags.aid
WHERE tags.tag IN ("green", "pink", "black");因为两个表都有一个公共属性(即项目ID),所以可以使用内部联接来连接两个表,并根据两个表中的其他属性(在本例中是标记名)筛选结果。
上面的查询将为您提供带有任何绿色、粉红色或黑色标签的项目ID列表。
编辑
抱歉,我没看到你对相关的要求。如果您想知道在每篇文章中找到了多少个标记,请将其转换为一个GROUPed查询,并计算找到的标记数:
SELECT
articles.aid,
articles.headline,
COUNT(tags.tid)
FROM articles
INNER JOIN tags
ON articles.aid = tags.aid
WHERE tags.tag IN ("green", "pink", "black")
GROUP BY articles.aid;试试看情况..。
首先,建立数据库:
mysql> CREATE TABLE articles (aid integer auto_increment, headline varchar(32), key(aid));
Query OK, 0 rows affected (0.13 sec)
mysql> CREATE TABLE tags (tid integer auto_increment, aid integer, tag VARCHAR(16), key(tid));
Query OK, 0 rows affected (0.09 sec)
mysql> INSERT INTO articles (headline) values ("This is a green Article"), ("This is another Test");
Query OK, 2 rows affected (0.05 sec)
Records: 2 Duplicates: 0 Warnings: 0
mysql> SELECT * FROM articles;
+-----+-------------------------+
| aid | headline |
+-----+-------------------------+
| 1 | This is a green Article |
| 2 | This is another Test |
+-----+-------------------------+
2 rows in set (0.00 sec)
mysql> INSERT INTO tags (aid, tag) VALUES (1, "blue"), (1, "yellow"), (2, "blue"), (2, "yellow"), (2, "pink"), (2, "black");
Query OK, 6 rows affected (0.04 sec)
Records: 6 Duplicates: 0 Warnings: 0然后运行一些查询:
mysql> SELECT articles.aid, articles.headline, COUNT(tags.tid) FROM articles INNER JOIN tags ON articles.aid = tags.aid WHERE tags.tag IN ("green", "pink", "black") GROUP BY articles.aid;
+-----+----------------------+-----------------+
| aid | headline | COUNT(tags.tid) |
+-----+----------------------+-----------------+
| 2 | This is another Test | 2 |
+-----+----------------------+-----------------+
1 row in set (0.00 sec)
mysql> SELECT articles.aid, articles.headline, COUNT(tags.tid) FROM articles INNER JOIN tags ON articles.aid = tags.aid WHERE tags.tag IN ("green", "pink", "black", "yellow") GROUP BY articles.aid;
+-----+-------------------------+-----------------+
| aid | headline | COUNT(tags.tid) |
+-----+-------------------------+-----------------+
| 1 | This is a green Article | 1 |
| 2 | This is another Test | 3 |
+-----+-------------------------+-----------------+
2 rows in set (0.00 sec)https://stackoverflow.com/questions/12186419
复制相似问题