0

I want to run the following two queries in one:

SELECT id FROM user_settings WHERE ......
$id = id_from_query_above();
$value = 100; // this could be anything
INSERT INTO user_config (sid, value) VALUES($id, $value) ON DUPLICATE KEY UPDATE value=$value

(notice that I want to update if a row associating to the primary key has already been inserted).

1 Answer 1

1

You want the insert . . . select syntax:

INSERT INTO user_config(sid, value)
    SELECT id, $value
    FROM user_settings
    WHERE ......
    ON DUPLICATE KEY UPDATE value = $value;
Sign up to request clarification or add additional context in comments.

7 Comments

That worked perfectly, thank you - I didn't know I could use the SELECT statement with non-table rows (i.e $value). Is it possible to do something similar with multiple insertions/ updates?
This will do multiple insertions. I don't know what the question is about updates, but subqueries are allowed in update queries too.
I meant updates if the row has been inserted. Could you provide an example where this query can insert 2 rows?
@KeirSimmons . . . That is an example. The select can return multiple rows.
So what about the value of $value (as this would be different for each insertion)?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.