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 select row only if multiple rows exist in group

I am working with a database where multiple rows of data exist for the same related entity, in this case a user_id.

Example database

What I need to do is match user_ids with conditions on a per user basis rather than a per row basis..

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

For example, I need a list of users where they have rows with both:

meta_key = "utm_campaign" and meta_value = "Summer20222" 

but also where they have

meta_key = "utm_medium" and meta_value = "qr_code"

for the same user_id.

Essentially, I’m trying to report How many users have the utm_campaign of "Summer2022" AND have the utm_medium of "qr_code" in this table

>Solution :

Aggregate and assert both key-value requirements:

SELECT user_id
FROM yourTable
GROUP BY user_id
HAVING SUM(meta_key = 'utm_campaign' AND meta_value = 'Summer20222') > 0 AND
       SUM(meta_key = 'utm_medium' AND meta_value = 'qr_code') > 0;
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