user1260310
user1260310

Reputation: 2227

Php/mysql query join

I am trying to implement a tag system for items. The tags are contained in a table called tags and I have another table tagitem that links items to tags. An item can have multiple tags. When I display the item, I would like to list all the tags. My question is, is there any way to do this with one query? If I join the items result to the tags table, either I get multiple records for one item (corresponding to the multiple tags) or if I include a group by tag, I get one record but only the first tag.

The other way would be to do a second query just to get the tags but that seems inefficient.

Item table
Id | name

Tag table
Id | tag

Tagitem table
Id|itemid|tagid

Php

$sql = "select i.*,ti.*,t.*
FROM 'items' i
LEFT JOIN 'tagitem' ti
ON i.id=ti.itemid
LEFT JOIN  'tag' t
On ti.tagid=t.id
WHERE i.id='2'";

//returns multiple records

$sql.="group by i.id";

//returns only first tag

Thx for any suggestions.

Upvotes: 0

Views: 115

Answers (1)

David Grenier
David Grenier

Reputation: 1241

Try GROUP_CONCAT.

You should be able to select your tags as a subquery and group them together to form an array.

SELECT
    Item.name,
    GROUP_CONCAT (Tags.tag SEPERATOR ',') AS tags
FROM
    Item
    LEFT JOIN Tagitem ON Tagitem.itemid = Item.Id
    LEFT JOIN Tag ON Tagitem.tagus = Tag.Id
WHERE
    Item.Id = 2

Give that a shot and let me know what happens. I'm guessing at the table structure a bit, so it may require some tweaking.

Upvotes: 1

Related Questions