很好的一天。在连接表中插入数据时遇到问题。
这是我的桌子:

users table

    -----------------------
    |user_id   |FullName |
    -----------------------
    |1      | John    |
    |2      | Michael |
    |3      | Bryce   |

addresses table

    -----------------------------------------
    |address_id|    country    |    city     |
    -----------------------------------------
    |    1     |      USA      |    New-York |
    |    2     |     Russia    |    Moscow   |
    |    3     |    Germany    |    Berlin   |
    |    4     |      UK       |    London   |

This is the Junction table to connect the
    two now.

"user_address"

    ------------------------
    | user_id | address_id |
    ------------------------
    |   1     |      1     |
    |   1     |      2     |
    |   2     |      3     |
    |   3     |      1     |

我想连接他们然后我创建地址。所以,我需要在address table中创建一个新地址,然后将创建地址的ID放在junction中(不关心user_id,我只需要处理address_id)。
下面是一个用于创建地址的查询:
"INSERT INTO addresses (country, city) VALUES (?, ?) RETURNING id, country, city"

如您所见,我需要返回已创建地址的值以将其显示给我的消费者。
我怎样才能插入一个新地址,得到它的身份证,并把它放在我的路口?在单个查询中需要。

最佳答案

插入一个with子句会有帮助。

with ins AS
(
 INSERT INTO addresses (country, city)
     VALUES ('USA', 'New-York') RETURNING address_id, country, city
),
ins2 AS
(
 INSERT INTO user_address (address_id) select address_id from ins
)
select * from ins

注:
你说过
.. 不关心用户id,我只需要处理地址id
所以,我想你还有另一个机制要更新user_ids
DEMO

关于sql - PostgreSQL。在联结表中插入值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56285400/

10-13 04:58
查看更多