2

I have a linking table with rule_id to sub_rule_id as such:

rule_id | sub_rule_id --------------------- 1 | 1 2 | 1 2 | 2 2 | 3 3 | 3 3 | 4 

I want to be able to get all the sub_rule_ids which are linked to only one rule_is by rule_id. So if my rule_id = 1 then I expected no rows. And if rule_id = 2 then I should get just one. Tried to play with distinct and having and would not trouble you with a bad query.. I am sure there is an easy elegant way to do it.

Thanks in advance

1 Answer 1

3

You can group by sub_rule_id amd set the condition in the having clause:

select sub_rule_id from tablename group by sub_rule_id having count(distinct rule_id) = 1 

Or with NOT EXISTS if you want full rows:

select t.* from tablename t where not exists ( select 1 from tablename where sub_rule_id = t.sub_rule_id and rule_id <> t.rule_id ) 
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks @forpas , where would I add where rule_id = <some_rule_id> tried for both with 1 according to my example and I get my entire table minus the a 2nd row
Why the entire table minus the a 2nd row? What is the logic to exclude that row? Its sub_rule_id is 1 just like the 1st row. So they should both be excluded. The same for rows 4 and 5.
Thanks! Managed with the NOT EXISTS alternative

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.