Home   Best Sellers   Blogging   Coding & Design   Technology   SEO   Travel & living   Career   Videos   Tips   Calculators     
Home  »     »     »  How to concatenate field values based on a "GROUP BY" Field - How to use MySQL GROUP_CONCAT() function

How to concatenate field values based on a "GROUP BY" Field - How to use MySQL GROUP_CONCAT() function

Thursday, October 23, 2014

How to use MySQL GROUP_CONCAT() function
How to concatenate field values based on a "GROUP BY" Field




Let's understand this with an example

There is a table "tbl_Locations" having 2 fields Location and State





Location State
Kochi KL
AlleppyKL
ChennaiTN
CoimbatoreTN
TrivandrumKL

Task is to get the Locations under a state as a comma separated string

ie, to show as given below

State Locations
KL Kochi,Alleppy,Trivandrum
TNChennai,Coimbatore


You can do this by using the MySQL GROUP_CONCAT() function

SYNTAX:
GROUP_CONCAT([DISTINCT] expr [,expr ...]
[ORDER BY {unsigned_integer | col_name | expr}
[ASC | DESC] [,col_name ...]]
[SEPARATOR str_val])

GROUP_CONCAT function concatenates values within each group defined by GROUP BY clause.

MySQL QUERY:
SELECT State, GROUP_CONCAT(Location) as Locations FROM tbl_Locations GROUP BY State;


Result:
State Locations
KL Kochi,Alleppy,Trivandrum
TNChennai,Coimbatore

Reference : MySQL GROUP_CONCAT()
Power of Group_Concat



How to link to this page?
If you wish to link to this page from your website, simply Copy and paste the above HTML code to your web page. It will appear on your page as:
How to concatenate field values based on a "GROUP BY" Field - How to use MySQL GROUP_CONCAT() function.




Share this!




comments powered by Disqus

This Weeks 7 Popular Posts


Subscribe to Recent Posts by Email
Stay connected to CROZOOM with regular Email notices of new Techie articles and IT Jobs. Updates will be delivered to your Inbox as soon as they are posted online.

Enter Your Email Address:  

Delivered by FeedBurner   RSS Feed

Search this Blog   



Urgent Openings for PHP trainees, Andriod / IOS developers and PHP developers in Kochi Trivandrum Calicut and Bangalore. Please Send Your updated resumes to recruit.vo@gmail.com   Read more »