How do I list related blog posts ordered by the number of common tags?
I want to display a list of related blog posts and I want the list to be ordered by the number of common tags they have to the current post. Each post can have multiple tags associated to it. Here is my table structure:
[Posts] <-- [posts-to-tags-joining-table] --> [Tags]
I'm using PHP and MySQL - can I do this in one query?
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
assuming pid as the primary key in the posts table, tid as the primary key in the tags table, both foreign keys in the p2t (post to tag) table?
Risposta num. 1
Sure you can do it in one query:
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;