简体   繁体   中英

MySQL query returning detailed group_contact information (with join)?

I have query which return me color of the owner and his pet's numbers. How to return instead of

[Red][1,2] 

someting more detailed like

[Red][Rufus, Bali]

It's name of pet with join on id of the pet. Is possibile to make another Columns on every pet name? (without using few selects of courst)

CREATE TABLE pet (id INT, name VARCHAR(20));
insert into pet values (1,"Rufus");
insert into pet values (2,"Bali");
insert into pet values (3,"Lolo");

CREATE TABLE own (id INT, own_name VARCHAR(20), own_color VARCHAR(20));
insert into own values (1,"Me", "Red");
insert into own values (2,"Other owners" ,"Green");

CREATE TABLE pet_owner (id INT, id_pet INT, id_own INT);
insert into pet_owner values (1, 1, 1);
insert into pet_owner values (2, 2, 1);
insert into pet_owner values (3, 3, 2);

DROP procedure if exists `pet`;
DELIMITER $$
CREATE procedure `pet`() 
BEGIN
set @param = 1;
select o.own_color as color,
       (select group_concat(id_pet) from pet_owner po where po.id_own = @param) as pets
from own o
where o.id = @param;
END$$

call pet;
select o.own_color as color,
   (select group_concat(p.name) from pet_owner po join pet p ON p.id = po.id_pet where po.id_own = @param) as pets

Try the following--the keys are the aggregate GROUP_CONCAT function and the GROUP BY clause:

select o.own_color as color, group_concat(p.name) as pet_names
from own o
    inner join pet_owner po on o.id = po.id_own
    inner join pet p on po.id_pet = p.id
group by o.id;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM