create table role (
role varchar(20),
id int
);
insert into role (role, id) values ('Friend', 1);
insert into role (role, id) values ('Son', 2);
insert into role (role, id) values ('Daughter', 3);
insert into role (role, id) values ('Father', 4);
insert into role (role, id) values ('Mother', 5);
insert into role (role, id) values ('Brother', 6);
insert into role (role, id) values ('Sister', 7);
create table person (
persons varchar(20),
personid int
);
insert into person (persons, personid) values ('James', 1);
insert into person (persons, personid) values ('Peter', 2);
insert into person (persons, personid) values ('Joseph', 3);
insert into person (persons, personid) values ('Jeni', 4);
create table role_person (
roleid int,
personid int
);
insert into role_person (roleid, personid) values (2, 1);
insert into role_person (roleid, personid) values (2, 2);
insert into role_person (roleid, personid) values (4, 2);
insert into role_person (roleid, personid) values (6, 2);
insert into role_person (roleid, personid) values (6, 2);
insert into role_person (roleid, personid) values (3, 4);
insert into role_person (roleid, personid) values (4, 3);
我希望最终输出如下所示
final output
persons friend son daughter father mother brother sister James - Y - - - - - Peter - Y - Y - Y - Joseph - - - Y - - - Jeni - - Y - - - -
由于基础数据库是Maria DB,因此我无法使用数据透视功能。 请注意,人们可以增加或减少/ 而且,明天的角色会像祖父,妻子等增加。
不确定在存储的proc或查询中如何解决此问题。
我们可以使用XML数据类型来处理动态查询。
答案 0 :(得分:0)
那又怎么样:
select
p.persons,
case when 1 in (select 1 from role_person rp where rp.personid = p.personid and rp.roleid = 1) then 'Y' else '-' end as friend,
case when 1 in (select 1 from role_person rp where rp.personid = p.personid and rp.roleid = 2) then 'Y' else '-' end as son,
case when 1 in (select 1 from role_person rp where rp.personid = p.personid and rp.roleid = 3) then 'Y' else '-' end as daughter,
case when 1 in (select 1 from role_person rp where rp.personid = p.personid and rp.roleid = 4) then 'Y' else '-' end as father,
case when 1 in (select 1 from role_person rp where rp.personid = p.personid and rp.roleid = 5) then 'Y' else '-' end as mother,
case when 1 in (select 1 from role_person rp where rp.personid = p.personid and rp.roleid = 6) then 'Y' else '-' end as brother,
case when 1 in (select 1 from role_person rp where rp.personid = p.personid and rp.roleid = 7) then 'Y' else '-' end as sister
from person p;
结果:
persons friend son daughter father mother brother sister
James - Y - - - - -
Peter - Y - Y - Y -
Joseph - - - Y - - -
Jeni - - Y - - - -
答案 1 :(得分:0)
我认为到目前为止,无法在MariaDB中检索动态数目的列。
据我所知,此功能仅存在于:
答案 2 :(得分:0)
我通过使用临时表,更改每个字段的临时表并使用正确的参数进行更新来解决此问题。