Ad

How Do I List Related Blog Posts Ordered By The Number Of Common Tags?

- 1 answer

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?

Ad

Answer

What about...:

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?

Ad
source: stackoverflow.com
Ad