Reputation: 5664
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?
Upvotes: 1
Views: 32
Reputation: 222462
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
.
Upvotes: 1