I have three MySQL tables, one with data, one with tags and one with associations between those two, which seems to be common practice when storing tags. The tables look like this:
links:
+----+------------+------------+
| id | url | added |
+----+------------+------------+
| 2 | google.com | 2012-12-14 |
| 3 | cnn.com | 2001-02-13 |
+----+------------+------------+
tags:
+----+--------+
| id | tag |
+----+--------+
| 1 | search |
| 2 | news |
+----+--------+
taglink:
+----+--------+-------+
| id | linkid | tagid |
+----+--------+-------+
| 1 | 2 | 1 |
| 2 | 3 | 1 |
| 3 | 3 | 2 |
+----+--------+-------+
What I want to receive is the following table:
+----+------------+------------+--------+-------------+
| id | url | added | tagids | tags |
+----+------------+------------+--------+-------------+
| 2 | google.com | 2012-12-14 | 1 | search |
| 3 | cnn.com | 2001-02-13 | 1,2 | search,news |
+----+------------+------------+--------+-------------+
To do so I had this query:
select
links.*,
group_concat(taglink.id) as tagids,
group_concat(tags.tag) as tags
from links
join taglink on taglink.linkid=links.id
join tags on tags.id=taglink.tagid
but this gives me a single row with every tag used, like so:
+----+------------+------------+--------+-------------+
| id | url | addad | tagids | tags |
+----+------------+------------+--------+-------------+
| 2 | google.com | 2012-12-14 | 1,2 | search,news |
+----+------------+------------+--------+-------------+
Everything seems to be grouped, which is not what I was looking for. Does anybody know the solution?
You need to use
GROUP BYwith yourgroup_concatfunctions as follows, or they’ll behave unpredictably. Try this.Note that I’ve added some
ORDER BYitems to make the order of things predictable.Go fiddle: http://sqlfiddle.com/#!2/2b3b9/5/0