我想显示相关博客帖子的列表,我希望列表按照当前帖子的常用标签数量排序。每个帖子都可以有多个与之关联的标签。这是我的表结构:
[帖子]< - [posts-to-tags-joining-table] - > [标签]
我正在使用PHP和MySQL - 我可以在一个查询中执行此操作吗?
答案 0 :(得分:5)
当然,您可以在一个查询中执行此操作:
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;
答案 1 :(得分:0)
怎么样......:
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)表中的两个外键?