PostgreSQL。在交汇处插入值 table
PostgreSQL. Insert valuse in junction table
美好的一天。我在连接 table.
中插入数据时遇到了一些问题
这是我的 tables:
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"
如您所见,我需要 return 已创建地址的值才能显示给我的消费者。
如何插入新地址、获取其 ID 并将其放入我的交界处?在单个查询中是理想的。
插入一个 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
注:
你说
.. don't care about user_id, I just need to handle address_id
所以,我想你有另一种机制可以更新 user_ids
美好的一天。我在连接 table.
中插入数据时遇到了一些问题
这是我的 tables:
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"
如您所见,我需要 return 已创建地址的值才能显示给我的消费者。
如何插入新地址、获取其 ID 并将其放入我的交界处?在单个查询中是理想的。
插入一个 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
注:
你说
.. don't care about user_id, I just need to handle address_id
所以,我想你有另一种机制可以更新 user_ids