1

I want to grab all rows from table items where id > 100

SELECT `id` FROM `items` WHERE `id` > 100

And for each of these rows returned from above select, insert a new row into the item_tags table;

INSERT INTO `item_tags` (`item_id`, `tag_id`) VALUES (107, 123)
INSERT INTO `item_tags` (`item_id`, `tag_id`) VALUES (114, 123)
.
.
.
INSERT INTO `item_tags` (`item_id`, `tag_id`) VALUES (299, 123)

Can I do this in a single query in MySQL?

1
  • You can use INSERT ... SELECT... anda since MySql 8.0.19 You can use INSERT .. TABLE Commented Jan 19, 2020 at 18:41

1 Answer 1

1

Consider the INSERT ... SELECT ... syntax:

INSERT INTO `item_tags` (`item_id`, `tag_id`) 
SELECT `id`, 123 FROM `items` WHERE `id` > 100

This will insert one record in item_tags for each record in items having id > 100, with a fixed value of 123 for column tag_id.

Sign up to request clarification or add additional context in comments.

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.