MySQL查询返回详细的group_contact信息(带连接)?

时间:2014-03-26 11:59:30

标签: mysql sql

我有查询返回主人的颜色和他的宠物的数字。如何返回而不是

[Red][1,2] 

更详细一些

[Red][Rufus, Bali]

这是加入宠物身份的宠物的名字。是否有可能在每个宠物名称上再制作一个列? (没有使用少数选择)

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;

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

尝试以下方法 - 键是聚合的GROUP_CONCAT函数和GROUP BY子句:

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;