开发者

Select related Elements Attributes as String

I have an items Table and a Tags table. Now what I would like is to have one Select that gets Items under a certain condition and for each item selects the related tags and puts them in a string to become a seperate field.

Example:

table_items:
id   | title
---------------------------
01   | peter
---------------------------
02   | john
---------------------------
03   | cindy

tags:
id   | title
---------------------------
01   | tall
---------------------------
02   | tiny
---------------------------
03   | blone
---------------------------
04   | loud
---------------------------
05   | ...

tags_to_items:
itemid | tagid
---------------------------
01     | 02
---------------------------
01     | 04
---------------------------
02     | 01
...

I think you get the point.

Now I want a result like this:
itemid | title   | tags
---------------------------
01     | peter 开发者_StackOverflow社区  | tiny, loud
---------------------------
01     | john    | tall, fast, bored

Can I do this with just MySQL? How?


In MySQL, you need GROUP_CONCAT function to do that.

Something like:

select ti.id, ti.title, group_concat(t.title)
  from table_items ti
 inner join tag_to_items tti on (ti.id = tti.itemid)
 inner join tags t on (t.id = tti.tagid)
 group by ti.id, ti.title
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜