I'm implementing a Tag System for my website, using PHP + MySQL.
In my database, I have three tables:
posts
| id | title | datetime |
|---|
Primary Key: id
tags
| id | tag | slug |
|---|
Primary Key: id | Key: slug
tagsmap
| id | tag |
|---|
Primary Key: both
(id = post's id in posts; tag = tag's id in tags)
Every post may have one or more tags, or no tags, associated to it.
Now I need to select - and show on the same page - the last 10 (no less, no more) published posts and all the tags associated to those posts.
This is what I've tried:
SELECT
p.title,
t.slug,
t.tag
FROM
posts p
LEFT JOIN tagsmap tm ON p.id = tm.id
LEFT JOIN tags t ON tm.tag = t.id
WHERE
p.datetime <= NOW()
ORDER BY
p.id DESC
LIMIT
10
It works, but, doing so, posts having two tags are showed twice, while I need to show each post just once.
Then I've added
GROUP BY p.id
But, this way, I get only one tag for each post.
I don't know how to solve this problem (I'm not very experienced with MySQL).
Would you give me any suggestions?
P.S.: What I need is a SQL-side (not PHP-side) solution (the best in terms of performance). Nevertheless, any further suggestions would be much appreciated.