SQL: INSERT INTO table(...) VALUES (...) with data retrieved from other tables

user8555937 :

Thank you for passing by. I know basic SQL syntax and I can't seem to find a way to accomplish this task.

I need to create a stored procedure which inserts data from one table in another, amid retrieving data from many others. Suppose I have these tables with columns:

  1. users

    • name (varchar)
    • sub_id (int)
    • dub_id (int)
  2. tmp_users

    • name (varchar)
    • sub_name (varchar)
    • dub_name (varchar)
  3. subs

    • id (int)
    • name (varchar)
  4. dubs

    • id (int)
    • name (varchar)

Translated in pseudocode I should do something like this:

INSERT INTO users (name, sub_id, dub_id)
ALL ROWS FROM tmp_users VALUES (
    name = tmp_users.name, 
    sub_id = SELECT id FROM subs WHERE tmp_users.sub_name = subs.name,
    dub_id = SELECT id FROM dubs WHERE tmp_users.dub_name = dubs.name,
)

In wording I need to insert into users all rows from tmp_users, to keep the col tmp_users.name, but retrieve the afferent ids of all other tables based on *_name column. How should I approach this task?

GMB :

It seems like you are looking for the INSERT ... SELECT syntax:

INSERT INTO users (name, sub_id, dub_id)
SELECT 
    tu.name,
    s.id,
    d.id
FROM tmp_users tu
LEFT JOIN subs s ON s.name = tu.sub_name
LEFT JOIN dubs d ON d.name = tu.dub_name

This brings all rows from tmp_users, then attempt to recover the corresponding sub_id and dub_id. For each row returned by the select, a record is inserted in users. A good thing about this syntax is that you can run the select query independently first, to see what would be inserted.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=371624&siteId=1