Mysql query group data in a field -


i have table this

create table `users_customers`(     `user_id` varchar(50) not null,     `customer_id` varchar(15) not null,     primary key(`user_id`, `customer_id`),     index user_id_index (`user_id`),     index customer_index (`customer_id`),     foreign key (`user_id`) references `users`(`id`) on delete cascade,     foreign key (`customer_id`) references `customers`(`id`) on delete cascade ); 

with data

users_customers user_id       customer_id -------------------------- 1             1 2             1 1             2 1             3 2             3 ... 

i query table , produce results this

user_id        customers ------------------------- 1              1,2,3 2              1,3 ... 

i have looked @ concat() function, still don't know how reflect want.

you use group_concat function this. group values , return them string.

so query like

select user_id, group_concat(customers)   users_customers group user_id 

if want values in order, can add order by group_concat, or if want different separator comma, can add separator definition.

you can prepend column distinct if field may contain duplicate values , want them once.

select user_id, group_concat(distinct customers order customers desc separator ';')   users_customers group user_id 

Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

c# - Retrieve google contact -

javascript - How to insert selected radio button value into table cell -