我想显示相关博客文章的列表,并且我希望该列表按它们对当前文章的常用标签数量进行排序。每个帖子可以有多个与之关联的标签。这是我的表结构:
[帖子] <-- [posts-to-tags-joining-table] --> [标签]
我正在使用 PHP 和 MySQL - 我可以在一个查询中执行此操作吗?
当然你可以在一个查询中做到这一点:
SELECT postid, count(tagid) as common_tag_count
FROM posts_to_tags
WHERE tagid IN (SELECT tagid FROM posts_to_tags WHERE postid = 2)
GROUP BY postid ORDER BY common_tag_count DESC;
关于什么...:
SELECT COUNT(*) AS numcommon, posts.pid, posts.post FROM posts
INNER JOIN p2t ON p2t.pid = posts.pid
WHERE p2t.tid IN
(SELECT p2t.tid FROM p2t
INNER JOIN posts ON p2t.pid = posts.pid
WHERE posts.pid = 1)
AND posts.pid != 1
GROUP BY posts.pid
ORDER BY numcommon
假设 pid 作为 posts 表中的主键, tid 作为 tags 表中的主键,p2t(post to tag)表中的两个外键?