简体   繁体   中英

Conditional INSERT INTO for Postgres

I use Postgres 12 and I have two tables users u and sessions s with the following columns s.user_id (FK) ==> u.user_id .

I would like to insert a session, in case the password is correct and I found this type of statement:

INSERT INTO sessions (c1, c2, c3)
SELECT ??? FROM sessions
WHERE NOT EXISTS(
          SELECT * FROM users WHERE users.pwsha256 = "1234..."
    )
LIMIT 1;

This looks promising, but how would I bring over u.user_id from users to the INSERT INTO to reference them? Any help is highly appreciated!

You should not only verify the password, but also check that the username is correct:

INSERT INTO sessions
   (user_id, ...)
VALUES (
   (SELECT id FROM users
    WHERE username = '...'
      AND users.pwsha256 = '1234...'),
   ...);

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM