美好的一天。我在联结表中插入数据时遇到麻烦。
这是我的桌子:
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
中创建一个新地址,并将它们放置在结点中(不必关心user_id
,我只需要处理address_id
)就可以了。< / p>
这是我用于创建地址的查询:
"INSERT INTO addresses (country, city) VALUES (?, ?) RETURNING id, country, city"
如您所见,我需要返回创建地址的值以将其显示给我的使用者。
我如何插入新地址,获取其ID并将其放入我的路口?在单个查询中是理想的。
答案 0 :(得分:2)
插入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
注意:
您说
..不在乎user_id,我只需要处理address_id
所以,我想您还有另一种机制来更新user_ids