[英]Merge tables by inserting null values for columns where no value can be derived from the merging tables?
I have two different tables and i decided to merge them into one table... 我有两个不同的表,我决定将它们合并到一个表中。
the birth table has 出生表有
id, name, country, birthday_date, description, link ID,名称,国家/地区,生日日期,描述,链接
the death table has 死亡表有
id, name, country, death_date, description, link ID,名称,国家/地区,死亡日期,描述,链接
and i want to merge them into a single table with the structure 我想将它们合并到具有结构的单个表中
id, name, country, bdate, ddate, description, link. ID,名称,国家/地区,日期,日期,说明,链接。
The link from each table has a unique value so i have to merge the tables using the link. 每个表的链接都有一个唯一的值,所以我必须使用链接合并表。 I tried many queries but resulted in wrong results. 我尝试了许多查询,但结果错误。
Both the birth and death table can have same names and some names may have present in either only birth or death table. 出生表和死亡表都可以具有相同的名称,并且某些名称可能只在出生表或死亡表中出现。
If then, How can i merge them and updating a null date for a column that has no value on any of the two old tables? 如果是的话,我该如何合并它们并更新两个旧表中没有值的列的空日期?
Assuming that your new id
has AUTO_INCREMENT
this solution using CROSS JOIN
and COALESCE
should work for you. 假设您的新id
具有AUTO_INCREMENT
则使用CROSS JOIN
和COALESCE
解决方案将为您工作。 name
, country
and description
from death
will be ignored, if available in birth
. death
时的name
, country
和description
(如果有birth
将被忽略。
INSERT INTO new_table ( name, country, bdate, ddate, description, link )
(
SELECT
COALESCE(b.name, d.name),
COALESCE(b.country, d.country),
b.birthday_date,
d.death_date,
COALESCE(b.description, d.description),
COALESCE(b.link, d.link)
FROM birth b
CROSS JOIN death d ON ( d.link = b.link )
)
Alternatively, insert all rows from birth
: 或者,从birth
插入所有行:
INSERT INTO new_table ( name, country, bdate, ddate, description, link )
(
SELECT name, country, birthday_date, NULL, description, link
FROM birth
)
Then update those rows with a `death_date´ if available: 然后使用“ death_date”更新这些行(如果可用):
UPDATE new_table nt
SET ddate = (SELECT death_date FROM death d WHERE d.link = nt.link )
Finally, add all rows from death
, that have no entry in birth
: 最后,添加death
所有没有birth
:
INSERT INTO new_table ( name, country, bdate, ddate, description, link )
(
SELECT name, country, NULL, death_date, description, link
FROM death d
WHERE NOT EXISTS ( SELECT NULL
FROM new_table
WHERE link = d.link
)
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.