我正在研究MySQL中的db,并且需要来自一行中几个表的数据。这是与相关数据库相关的问题:
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
a.own_color as 'color',
(select id_pet from pet_owner where id_own = @param) as 'pets'
from own as a where a.id = @param;
END$$
call pet;
子查询返回超过1行
如何在一行中收集所有宠物ID(每个id_pet可以在其他列中)
答案 0 :(得分:4)
您想使用group_concat()
:
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;
请注意,我对查询进行了一些更改:
o
代表所有者,而不是a
)。group_concat()
答案 1 :(得分:0)
您可以使用GROUP_CONCAT。
-- ...
select
a.own_color as 'color',
(select group_concat(id_pet,',') from pet_owner where id_own = @param) as 'pets'
from own as a where a.id = @param;
但要注意结果有1024字节的限制。要解决此问题,请在查询之前运行此查询:(根据需要更改2048)。
set group_concat_max_len=2048