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

Get all elements which have both values grouped by ParentId

I have the following problem:

I have a relation table like this:

ParentId | ValueId
1          1   
1          2
2          3
2          4
2          1

Then, I want to get the ParentId who have exactly the values which query say, no more, no less.

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

I have this query actually:

SELECT "ParentId" FROM public."ParentValueRelation"
WHERE "ValueId" = 1 AND "ValueId" = 2
GROUP BY "ParentId"

Expected to receive 1 but getting null

Answer in sequelize could be great but not necessary

>Solution :

There are number of ways to do this in Postgres. Like this for instance:

SELECT "ParentId" FROM public."ParentValueRelation"
WHERE "ValueId" = 1 OR "ValueId" = 2
GROUP BY "ParentId"
HAVING COUNT("ValueID")=2

If there are duplicates in the table, you need to replace the having clause with

HAVING COUNT(DISTINCT "ValueID")=2

Best regards,Bjarni

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