从表Postgresql

时间:2019-04-14 13:06:17

标签: postgresql

我是Nubie。 我想通过从多个表中绘制数据来创建一个postgresql表

表1

| partner_id | **project_id** | partner_fund | partner_date |
| 12345      | 099            | 12345.70     | 2003-02-02   |

表2

| partner_id | partner_name
| 12345      | monster.inc

表3

| **package_id** | **project_id** |
| 099a           | 099            |

表4

| **package_id** | project_name
| 099a           | kill some one

* package_id对应于project_id

我想制作一张这样的桌子:

| (if)partner_id | (get)partner_name | (if)project_id (corresponding to package_id)| (get)project_name | partner_fund | partner_date

因此,如果第一行显示partner_id,下一列显示partner_name,等等。请提供帮助。谢谢。

1 个答案:

答案 0 :(得分:0)

您可以使用CREATE TABLE ... AS语法通过SELECT查询创建新表:

CREATE TABLE new_table AS
SELECT
    table1.partner_id,
    table2.partner_name,
    table3.project_id,
    table3.project_name,
    table1.partner_fund
FROM table1
INNER JOIN table2 ON (table1.partner_id = table2.partner_id)
INNER JOIN table3 ON (table1.project_id = table3.project_id)
;

...然后您还可以将主键添加到新表中,例如:

ALTER TABLE new_table ADD PRIMARY KEY (partner_id, project_id);

在更新问题后查询:

CREATE TABLE new_table AS
SELECT
    table1.partner_id,
    table2.partner_name,
    table1.project_id,
    table4.project_name,
    table1.partner_fund,
    table1.partner_date
FROM table1
INNER JOIN table2 ON (table1.partner_id = table2.partner_id)
INNER JOIN table3 ON (table1.project_id = table3.project_id)
INNER JOIN table4 ON (table3.package_id = table4.package_id)
;