I need to add a new row for all post_ids that equal specific condition. So there is a table with post_id, meta_key and meta_value
| id | post_id | meta_key | meta_value |
|---|---|---|---|
| 1 | 100 | page-type | city |
| 2 | 100 | banner | "banner" |
| 3 | 101 | page-type | city |
| 4 | 102 | page-type | city |
| 5 | 102 | banner | "new banner |
| 6 | 111 | page-type | non-city |
| 7 | 111 | banner | "non-citybanner" |
I need to add for post_id that has meta_key = "page-type" and meta_value = "city" while meta_key = "banner" does not exist. In this example I should have a new row
| id | post_id | meta_key | meta_value |
|---|---|---|---|
| 8 | 101 | banner | "my new banner" |
Of course the table contains about 200K such rows 🙂
Any suggestions?
>Solution :
INSERT INTO
post (
post_id,
meta_key,
meta_value
)
SELECT
post_id,
'banner',
'"my new banner"'
FROM
your_meta_table
GROUP BY
post_id
HAVING
MAX(CASE WHEN meta_key = 'banner' THEN 1 ELSE 0 END) = 0
AND
MAX(CASE WHEN meta_key = 'page-type' AND meta_value = 'city' THEN 1 ELSE 0 END) = 1
Or, preferably…
INSERT INTO
post (
post_id,
meta_key,
meta_value
)
SELECT
post_id,
'banner',
'"my new banner"'
FROM
your_posts_table
WHERE
NOT EXISTS (
SELECT *
FROM your_meta_table
WHERE post_id = your_posts_table.post_id
AND meta_key = 'banner'
)
AND EXISTS (
SELECT *
FROM your_meta_table
WHERE post_id = your_posts_table.post_id
AND meta_key = 'page-type'
AND meta_value = 'city'
)