Keir Simmons
Keir Simmons

Reputation: 1684

MySQL: Insert data into table, some data comes from another table (relational)

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).

Upvotes: 0

Views: 65

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1269713

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;

Upvotes: 1

Related Questions