MYSQL INSERT INTO 现有表数据来自 2 个单独的表 ON id

标签 mysql sql join insert

我有一个空表“new_foobar”。它有“fbc_primary_key”、“fbc_two”、fbc_three 和 fbc_four 列。

fbc_three 默认为“苹果”

然后我有一个表“foo”,其中包含列“fc_pimary_key”、“fc_two”。以及一个包含列“bc_primary_key”、“bc_two”、“bc_three”的表“bar”。

fbc_primary_key、bc_primary_key、fc_primary_key,都是各自表的主键。

如何将 fc_two 插入 fbc_two,并将 bc_three 插入 fbc_four。

TABLE foo
fc_primary_key | fc_two |
-------------------------
1              | hello  |
2              | goodbye|

TABLE bar
bc_primary_key | bc_two | bc_three |
------------------------------------
1              | abc    | 123      |
2              | def    | 456      |

*NOTE bar and foo have a 1-to-1 relationship.


TABLE foobar
fbc_primary_key | fbc_two | fbc_three | fbc_four |
---------------------------------------
/* empty */

...AFTER SOME SQL MAGIC....

TABLE foobar
fbc_primary_key | fbc_two | fbc_three | fbc_four |
---------------------------------------------------
1               | hello   | apple     | 123      |
2               | goodbye | apple     | 456      |

我遇到的问题是,如何让数据列落在 foobar 列下。

最佳答案

insert into foobar
select 
  ifnull(f.fbc_primary_key, b.fbc_primary_key), 
  fbc_two, 
  fbc.three
from 
  foo f
  full outer join bar b on b.fbc_primary_key  = f.fbc_primary_key 

如果只想要两个表中都存在的记录,可以使用内连接。你也可以跳过 ifnull,因为 f 和 b 都有一个 id。

关于MYSQL INSERT INTO 现有表数据来自 2 个单独的表 ON id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6078128/

相关文章:

mysql - 由于多个、充满 JOIN 的子查询而导致查询缓慢

sql - 使用别名与不使用 HAVING 之间是否存在性能差异

如果另一个字段为空,SQL 将使用某个字段

mysql计数相关表

mysql - 加入查询 laravel 4.2 的 Where 子句

mysql - SQL SUM 连接问题

mysql - 如何在SQL查询中添加固定位置列?

mysql - 强制表参与的最佳方式

mysql - 错误: 'Access denied for user ' root' @'localhost' (using password: YES)'

php - else 条件不做任何事情