我面临的问题的模拟表格和数据:
create table table1 (people varchar(10), special_id varchar(20));
create table table2 (special_id varchar(20), dependent_value int8, value_wanted varchar(5));
insert into table1 values
('person1', 'abc'),
('person1', 'abc'),
('person1', 'abc'),
('person1', 'abc'),
('person1', 'bbb'),
('person1', 'bbb'),
('person1', 'ccd');
insert into table2 values
('abc', '02', 'boom'),
('abc', '01', 'zoom'),
('bbb', '01', 'woom'),
('abc', '03', 'whom');
这就是我想要达到的结果:
+---------+------------+---------+---------+
| people | special_id | code_01 | code_02 |
+---------+------------+---------+---------+
| person1 | abc | zoom | boom |
| person1 | abc | zoom | boom |
| person1 | abc | zoom | boom |
| person1 | abc | zoom | boom |
| person1 | bbb | woom | NULL |
| person1 | bbb | woom | NULL |
| person1 | ccd | NULL | NULL |
+---------+------------+---------+---------+
使用模拟表格,我可以通过这样做来创建上面的表格:
select t1.*, t2.value_wanted as code_01, t2_1.value_wanted as code_02
from table1 t1
left join table2 t2
on t2.special_id = t1.special_id and t2.dependent_value = '01'
left join table2 t2_1
on t2_1.special_id = t1.special_id and t2_1.dependent_value = '02';
问题是为了添加code_03
和其他列,我必须不断地添加左连接。这看起来效率不是很高。有没有更好的方法在考虑性能的情况下做到这一点?
转载请注明出处:http://www.xingnongyuan.com/article/20230430/1373368.html