MySQL - String concat multiple rows using group_concat

If you are implementing a tagging system like what you see with WordPress, then you may have a requirement to fetch all the tags of each article in the blog when displaying the blog. As each article has many tags, one option is to first fetch all the articles and for each article fetch the list of tags. However, there is a better way to do this in one single SQL when using MySQL.
MySQL has the function group_concat that allows one to condense a set of rows into one single row by concatenating the list of values.
The SQL will be something like
select article_id,article_title,article_text,(select group_concat(tag) from tags t where t.article_id = a.id) tags from articles a …;
Here, the subselect used for the tags column is what I am talking about. It uses the group_concat to concatenate all the tags together. By default it uses ‘,’ as the default separator.
To specify a separator explicitly, use SEPARATOR followed by the string value that should be inserted between group values.
This functionality is also very helpful for MySQL injection geeks in case of there  is only one row which can be displayed in the webpage being injected. 

2 comments:

  1. Great on site tip. I've always believed that you need to start with on-site seo services and use off-site techniques, like link building, in support of that. Once you have a well designed web site and great content it will be much easier to get back links and improve your serp. Thanks

    ReplyDelete
  2. brillant piece of information, I had come to know about your web-page from my friend hardkik, chennai,i have read atleast 9 posts of yours by now, and let me tell you, your webpage gives the best and the most interesting information. This is just the kind of information that i had been looking for, i'm already your rss reader now and i would regularly watch out for the new posts, once again hats off to you! Thanx a million once again, Regards, Single Row Function

    ReplyDelete