db2 - SQL dynamic where clause based on parent table column -
i've below 2 tables , need single sql these requirements (no union
).
if check_child
false
, return rows parent table. if check_child
true
, check if there reference row in child table , return parent row. if there no reference row in child table, don't return parent row.
parent table id int (pk) check_child boolean child table id int (pk) parent_id int (fk)
sample data:
parent table ------------ id check_child 1 false 2 true 3 true child table ----------- id parent_id 1 2
with sample data, query should return first 2 rows parent table because third row doesn't have reference row in child table.
a couple of alternatives:
select p.* parent p left outer join child c on c.parent_id = p.id p.check_child = 'false' or c.parent_id not null
or
select * parent p p.check_child = 'false' or ( p.check_child = 'true' , exists (select 1 child c c.parent_id = p.id) )
Comments
Post a Comment