使用部分来自现有数据的值创建新列并使用连接 SQL/BQ
Create new column with values partially from existing data and rest with a join SQL/BQ
主要Table:
ID
Table_Name
1
tb_1
2
tb_1
3
tb_1
4
tb_2
5
tb_2
6
tb_2
tb_1 :
a_ID
tb1_id
4
44
5
55
6
66
tb_2 :
b_ID
tb2_id
1
11
2
22
3
33
输出:
ID
Table_Name
tb1_id
tb2_id
1
tb_1
1
11
2
tb_1
2
22
3
tb_1
3
33
4
tb_2
44
4
5
tb_2
55
5
6
tb_2
66
6
是否可以使用三个 table 创建如上所述的输出?
例如:当在主 table 中创建新列 tb1_id 时,值是从 tb_1 table,如果在主要 table 中,ID 下的元素被标记为 tb_1 在 table_name 列下,然后 tb1_id 中的值将与 ID 列相同,然而对于非 tb_1 table,它应该取自 tb_1 table .
insert into output
as select
maintable.ID,
maintable.Table_Name
maintable.ID as tb1_id,
tb_1.a_id as tb2_id
from tb_1 a
inner join maintable on tb_1.a_id = maintable.ID
union
select
maintable.ID,
maintable.Table_Name
tb_2.b_id as tb1_id,
maintable.ID as tb2_id
from tb_2 b
inner join maintable on tb_2.b_id = maintable.ID
考虑以下方法
select t.id, t.table_name,
ifnull(tb1_id, id) as tb1_id,
ifnull(tb2_id, id) as tb2_id
from main_table t
left join tb_1 on id = a_id
left join tb_2 on id = b_id
如果应用于您问题中的示例数据 - 输出为
主要Table:
ID | Table_Name |
---|---|
1 | tb_1 |
2 | tb_1 |
3 | tb_1 |
4 | tb_2 |
5 | tb_2 |
6 | tb_2 |
tb_1 :
a_ID | tb1_id |
---|---|
4 | 44 |
5 | 55 |
6 | 66 |
tb_2 :
b_ID | tb2_id |
---|---|
1 | 11 |
2 | 22 |
3 | 33 |
输出:
ID | Table_Name | tb1_id | tb2_id |
---|---|---|---|
1 | tb_1 | 1 | 11 |
2 | tb_1 | 2 | 22 |
3 | tb_1 | 3 | 33 |
4 | tb_2 | 44 | 4 |
5 | tb_2 | 55 | 5 |
6 | tb_2 | 66 | 6 |
是否可以使用三个 table 创建如上所述的输出? 例如:当在主 table 中创建新列 tb1_id 时,值是从 tb_1 table,如果在主要 table 中,ID 下的元素被标记为 tb_1 在 table_name 列下,然后 tb1_id 中的值将与 ID 列相同,然而对于非 tb_1 table,它应该取自 tb_1 table .
insert into output
as select
maintable.ID,
maintable.Table_Name
maintable.ID as tb1_id,
tb_1.a_id as tb2_id
from tb_1 a
inner join maintable on tb_1.a_id = maintable.ID
union
select
maintable.ID,
maintable.Table_Name
tb_2.b_id as tb1_id,
maintable.ID as tb2_id
from tb_2 b
inner join maintable on tb_2.b_id = maintable.ID
考虑以下方法
select t.id, t.table_name,
ifnull(tb1_id, id) as tb1_id,
ifnull(tb2_id, id) as tb2_id
from main_table t
left join tb_1 on id = a_id
left join tb_2 on id = b_id
如果应用于您问题中的示例数据 - 输出为