Wednesday, 11 March 2015

MySQL GROUP_CONCAT Function

MySQL GROUP_CONCAT(): Function returns a string with concatenated non-NULL value from a group.

Let’s take a look at the table vehicle_Driver.

We can find each vehicle_number having more than one driver_id.
i.e 1 vehicle contains more than one driver.

Desired Output:

id   vehicle_number    driver_id
1      HR55M6112       2,1,10

Want driver names to be displayed in place of driver_id look at driver_master.


Desired Output

vehicle_number  driver_name

HR55M6112       Abc,Xyz,Pqr

Query

SELECT m.vehicle_number,
(select GROUP_CONCAT(driver_name) from driver_master where driver_id in (select driver_id from vehicle_driver where vehicle_number=m.vehicle_number)) drivers
             FROM vehicle_driver m group by vehicle_number;