Search code examples
mysqlselectinsertsql-insertinsert-select

Combine INSERT with SELECT statement with custom values


I need to clean up my MySQL database and make a lot of new records based on the current state. I need to insert this:

INSERT INTO wp_postmeta (post_id, meta_key, meta_value) VALUES ($ID, "price_input_currency", "usd")

For each $ID I get from this selection:

SELECT ID FROM wp_posts AS posts
RIGHT JOIN wp_postmeta ON posts.ID = post_id
WHERE post_type = 'post'
AND meta_value LIKE '%$%' AND meta_key = 'price_range'

Is this possible through only a MySQL code? I've seen a bunch of "how to combine INSERT with SELECT, but none of them used just strings to insert, they always SELECTED ALL the fields they needed to insert... Any ideas?


Solution

  • You can use the INSERT INTO...SELECT construct, with constant string values for the meta_key and meta_value columns:

    INSERT INTO wp_postmeta (post_id, meta_key, meta_value)
    SELECT ID, 'price_input_currency', 'usd'
    FROM wp_posts AS posts
    RIGHT JOIN wp_postmeta
        ON posts.ID = post_id
    WHERE post_type = 'post' AND
        meta_value LIKE '%$%' AND meta_key = 'price_range'