gpt4 book ai didi

mysql - 如何将一个表连接到两个不同的表

转载 作者:行者123 更新时间:2023-11-29 20:54:08 24 4
gpt4 key购买 nike

我想将一个表连接到两个表,并希望结果采用以下格式,

ID    Name1    Name2     StatusOfName2Yearwise   Year 

我尝试过的是,

select t1.ID, t1.Name as 'Name1', t1a.Name as 'Name2', isnull(t2.Status,'N') as 'StatusOfName2Yearwise',Year
from
table_1 t1, table_1 t1a
LEFT JOIN table_3 t3 on t1a.id=t3.f_id
LEFT JOIN table_2 t2 on t1a.ID=t2.id,
table_4 t4 LEFT JOIN table_2 t2a on t4.Year=t2a.Fyr
where
t1.ID=t3.f_id
group by
t1.ID, t1.Name, t1a.Name, t2.Status ,Year
order by
t1.Name

此查询给出了 Name2 的状态,但它不是逐年的,我希望它是逐年的。如果有人知道请帮忙..

添加我从查询中获得的输出数据,

 ID           Name1        Name2        StatusOfName2Yearwise     Year
22 George Julie C 2015
22 George Julie C 2016
22 George Julie C 2017

预期结果应如下所示,

 ID           Name1         Name2        StatusOfName2Yearwise    Year
22 George Julie N 2015
22 George Julie N 2016
22 George Julie C 2017

最佳答案

在不知道表中数据的情况下,我试图推断其中可能包含的内容。

根据该测试数据,我构建了一个 SQL ( Sql Server ),它将给出预期的结果。

表与年份的完全联接可确保显示每年,即使 table_2 中没有对应的 Fyr 也是如此。

为了测试,变量表被赋予了稍微更有意义的名称。

DECLARE @table_1_user TABLE (id int, Name varchar(8));
DECLARE @table_2_userstatus TABLE (id int, Status char(1), Fyr char(4));
DECLARE @table_3_userrelation TABLE (id int, f_id int);
DECLARE @table_4_year TABLE (Year char(4));

insert into @table_1_user values
(22,'George'),
(23,'Julie');
insert into @table_2_userstatus values
(22,'C','2016'),
(22,'X','2017'),
(23,'N','2016'),
(23,'C','2017');
insert into @table_3_userrelation values (22,23);
insert into @table_4_year values ('2015'),('2016'),('2017');

select distinct
t1a.id as Id1,
t1b.id as Id2,
t1a.Name as Name1,
t1b.Name as Name2,
isnull(t2b.Status,'N') as StatusOfName2Yearwise,
q.Year
from (
select * from @table_3_userrelation t3
full outer join @table_4_year t4 on (1=1)
) q
left join @table_1_user t1a on (q.id = t1a.id)
left join @table_1_user t1b on (q.f_id = t1b.id)
left join @table_2_userstatus t2b on (q.f_id = t2b.id and q.Year = t2b.Fyr)
order by t1a.Name, t1b.Name, q.Year;

这将给出以下结果:

Id1     Id2     Name1       Name2       StatusOfName2Yearwise       Year
22 23 George Julie N 2015
22 23 George Julie N 2016
22 23 George Julie C 2017

关于mysql - 如何将一个表连接到两个不同的表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37767333/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com