Hello I use INSERT
with ON CONFLICT
for create or update data.
Example:
INSERT INTO users(office_id, f_name, l_name)
VALUES
(1, 'user1_f', 'u1_last'),
(2, 'user2_f', 'u2_last'),
(2, 'user3_f', 'u2_last')
ON CONFLICT(office_id, l_name)
DO UPDATE SET
f_name=EXCLUDED.f_name
But can I create also associated to users
for example profiles
table if user wasn't exist?
I mean if I don't have conflict, will be
INSERT INTO profiles(user_id, url) VALUES(user_id, 'google.com')
and user_id
will be id
from created user
I dont know is it possible. Thanks.
I solved it through Postgres WITH
from https://www.postgresql.org/docs/9.6/static/queries-with.html in next way:
WITH new_users AS (
INSERT INTO users(office_id, f_name, l_name)
VALUES
(1, 'user1_f', 'u1_last'),
(2, 'user2_f', 'u2_last'),
(2, 'user3_f', 'u2_last')
ON CONFLICT(office_id, l_name)
DO UPDATE SET
f_name=EXCLUDED.f_name
RETURNING *
), new_user_profile AS (
INSERT INTO profiles(user_id, created_at, updated_at)
SELECT id, current_timestamp, current_timestamp FROM new_users
ON CONFLICT (user_id) DO NOTHING
RETURNING *
)
SELECT * FROM new_users
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.