[英]MySQL Merging two tables with precedence
In a MySQL database, I have 2 tables with the following sample data. 在MySQL数据库中,我有2个表,其中包含以下示例数据。 The table key is variable_id.
表键是variable_id。
table_1 表格1
**variable_id** **release_id** 3 10 5 10
table_2 TABLE_2
**variable_id** **release_id** 1 01 2 15 3 15 4 20 5 25
I want to be able to merge the two tables, with the rows in table_1 having precedence over the rows in table_2. 我希望能够合并这两个表,table_1中的行优先于table_2中的行。
The result set should be: 结果集应该是:
**variable_id** **release_id** 1 01 2 15 3 10 4 20 5 10
Please help me with the MySQL SQL to accomplish this. 请帮我用MySQL SQL来完成这个。 I tried doing a union of left and right joins but it did not work.
我尝试了左右连接的联合,但它没有用。
You could take the rows from table_1
and then union all
them the extra rows from table_2
. 您可以从
table_1
获取行,然后将union all
这些行与table_2
的额外行table_2
。 Clunky, but should get the job done: 笨重,但应该完成工作:
SELECT *
FROM table_1
UNION ALL
SELECT *
FROM table_2
WHERE variable_id NOT IN (SELECT variable_id FROM table_1)
SELECT table_2.variable_id,
IFNULL(table_1.release_id, table_2.release_id) release_id
FROM table_2
LEFT JOIN table_1
ON table_2.variable_id = table_1.variable_id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.