Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

MySql query to insert row with multiple conditions

I need to add a new row for all post_ids that equal specific condition. So there is a table with post_idmeta_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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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'
  )
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading