1

Let's say I have a "source table" which holds some rows, in this case four. Now I'd like to insert new rows into a "target table" for each of the rows from the source table.

My current statement is:

SET @id = 1;
INSERT INTO target_table (id, value)
VALUES (@id, 1),
       (@id, 2),
       (@id, 3),
       (@id, 4);

However I'd like to do something like this...

SET @id = 1;
myResultSet = SELECT value FROM source_table;
FOR EACH value in myResultSet
    INSERT INTO target_table (@id, @value)
END
3
  • Why do you want to have all id values as 1 in your target_table ? Commented Oct 11, 2018 at 9:39
  • It's the ID of a "fixed employee" who can have multiple permissions. Commented Oct 11, 2018 at 9:42
  • 1
    Ok. you simply need to use a Insert ... Select statement Commented Oct 11, 2018 at 9:43

3 Answers 3

1

You can use Insert ... Select statement:

INSERT INTO `target_table` (`id`, `value`) 
SELECT 1, `value` 
FROM `source_table` 

Completely possibilities of this statement can be seen from the syntax below:

INSERT [LOW_PRIORITY | HIGH_PRIORITY] [IGNORE]
    [INTO] tbl_name
    [PARTITION (partition_name [, partition_name] ...)]
    [(col_name [, col_name] ...)]
    SELECT ...
    [ON DUPLICATE KEY UPDATE assignment_list]

value:
    {expr | DEFAULT}

assignment:
    col_name = value

assignment_list:
    assignment [, assignment] ...
Sign up to request clarification or add additional context in comments.

Comments

1
INSERT INTO target_table ( id, value )
SELECT  row_number() OVER (order by <whatever>) , value FROM source_table

or

INSERT INTO target_table( id, value )
SELECT  1, value FROM source_table

depending on what you mean

Comments

1
INSERT INTO target_table( id, value )
SELECT  1, value FROM source_table

Comments

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.