I have 2 tables which I want to join and return only those records which:
- Have the same value with other records in one of the columns.
- Have certain values in other column.
These are my requests:
List only those records which have the same value with other records in grnz column:
SELECT * FROM violations.violation_decrees AS vd JOIN violations.violations_reports AS vr ON vd.violation_id = vr.violation_id WHERE vd.grnz IN (SELECT grnz FROM violations.violation_decrees AS vd GROUP BY vd.grnz HAVING COUNT(id) > 1) ORDER BY vd.grnz
List only those records which have violation_status_id equal to 10 or 11
SELECT * FROM violations.violation_decrees AS vd JOIN violations.violations_reports AS vr ON vd.violation_id = vr.violation_id WHERE vr.violation_status_id IN (10,11) ORDER BY vd.grnz
But when I try to combine them
SELECT * FROM violations.violation_decrees AS vd JOIN violations.violations_reports AS vr ON vd.violation_id = vr.violation_id WHERE vd.grnz IN (SELECT grnz FROM violations.violation_decrees AS vd GROUP BY vd.grnz HAVING COUNT(id) > 1) AND vr.violation_status_id IN (10,11) ORDER BY vd.grnz
condition
vd.grnz IN (SELECT grnz FROM violations.violation_decrees AS vd GROUP BY vd.grnz HAVING COUNT(id) > 1)
is completely ignored and output is similar to request N 2.
Any advice?
Advertisement
Answer
During the building of the schema I found an error: I was picking duplicates before implementing the value filter.
Here is the correct request:
SELECT vr.violation_status_id, vd.* FROM violations.violation_decrees AS vd JOIN violations.violations_reports AS vr ON vd.violation_id = vr.violation_id WHERE vd.grnz IN (SELECT vd.grnz FROM violations.violation_decrees AS vd JOIN violations.violations_reports AS vr ON vd.violation_id = vr.violation_id WHERE vr.violation_status_id IN (10,11) GROUP BY vd.grnz HAVING COUNT(vd.grnz) > 1) AND vr.violation_status_id IN (10,11) ORDER BY vd.grnz