PostgreSQL结合表

时间:2013-04-17 01:48:54

标签: sql postgresql

我对将一个表合并到另一个表有点困惑。我的两个表看起来像这样:

Table A                                         Table B
id | name | likes | email | username            id | name | email   | username
1  | joe  |  3    |  null | null                1  | ben  | a@co.co | user


Result: Table A
id | name | likes | email   | username
1  | joe  | 3     | null    | null
2  | ben  | null  | a@co.co | user

我的问题是我不想覆盖表A中的属性。这是一个简单的UNION吗?

1 个答案:

答案 0 :(得分:3)

您只需执行INSERT INTO..SELECT声明,

即可
INSERT INTO TableA(id, name, likes, email, username)
SELECT id, name, NULL AS likes, email, username
FROM TableB

它的作用是将所有记录从TableB复制到TableA。但是如果你只想要投影的记录,那么一个简单的UNION就可以了。

SELECT id, name, likes, email, username FROM tableA
UNION
SELECT id, name, NULL AS likes, email, username FROM TableB