MySQL 按单个唯一字段联合表
MySQL UNION tables by a single unique field
我想联合具有相同列的表,例如:
table1
id var1 var2
1 green red
2 blue NULL
table2
id var1 var2
2 NULL pink
3 red blue
我的结果应该是这样的:
id var1 var2
1 green red
2 blue pink
3 red blue
A "normal" UNION 创建以下结果:
id var1 var2
1 green red
2 blue NULL
2 NULL pink
3 red blue
... 有两个 id = 2 条目,因为 id = 2 的两行不相同。但是,我希望只有一行 ID 为 2。
我目前的解决方法如下:
步骤 1
CREATE OR REPLACE VIEW temp AS
SELECT id FROM table1
UNION
SELECT id FROM table2;
步骤 2
SELECT t1.id, IFNULL(t2.var1, t3.var1) AS var1, IFNULL(t2.var2, t3.var2) AS var2
FROM temp AS t1
LEFT JOIN table1 AS t2 ON t1.id = t2.id
LEFT JOIN table2 AS t3 ON t1.id = t3.id;
我不敢相信这是解决问题的最聪明的方法,因为它是如此常见。当表格或变量的数量增加时,这真是令人头疼。
感谢任何聪明的想法!
这是使用 not exists
的一种方法:
select id, var1, var2
from table1
union all
select id, var1, var2
from table2 t2
where not exists (
select 1
from table1 t1
where t1.id = t2.id
)
这是另一个 outer join / null
检查:
select id, var1, var2
from table1
union all
select t2.id, t2.var1, t2.var2
from table2 t2
left join table1 t1 on t2.id = t1.id
where t1.id is null
我想联合具有相同列的表,例如:
table1
id var1 var2
1 green red
2 blue NULL
table2
id var1 var2
2 NULL pink
3 red blue
我的结果应该是这样的:
id var1 var2
1 green red
2 blue pink
3 red blue
A "normal" UNION 创建以下结果:
id var1 var2
1 green red
2 blue NULL
2 NULL pink
3 red blue
... 有两个 id = 2 条目,因为 id = 2 的两行不相同。但是,我希望只有一行 ID 为 2。
我目前的解决方法如下:
步骤 1
CREATE OR REPLACE VIEW temp AS
SELECT id FROM table1
UNION
SELECT id FROM table2;
步骤 2
SELECT t1.id, IFNULL(t2.var1, t3.var1) AS var1, IFNULL(t2.var2, t3.var2) AS var2
FROM temp AS t1
LEFT JOIN table1 AS t2 ON t1.id = t2.id
LEFT JOIN table2 AS t3 ON t1.id = t3.id;
我不敢相信这是解决问题的最聪明的方法,因为它是如此常见。当表格或变量的数量增加时,这真是令人头疼。
感谢任何聪明的想法!
这是使用 not exists
的一种方法:
select id, var1, var2
from table1
union all
select id, var1, var2
from table2 t2
where not exists (
select 1
from table1 t1
where t1.id = t2.id
)
这是另一个 outer join / null
检查:
select id, var1, var2
from table1
union all
select t2.id, t2.var1, t2.var2
from table2 t2
left join table1 t1 on t2.id = t1.id
where t1.id is null