I have a little problem with the SQL query, and I thought that I would ask the wisdom of the crowd to see what I did not see. I'm sure the below works, but it seems very bad, and I wonder if there is a more reasonable way (ideally, using joins instead of subselects).
Problem
Let's say I have some tables:
Prize - PrizeId RulePrize_Map - PrizeId - RuleId Rule - RuleId Conditional - ConditionalId - RuleId - InputId - ExpectedValue (bit) Input - InputId
A Prize won when at least one Rule is true. A Rule true when all of its Conditionals are true. A Conditional is โtrueโ when its InputId present or absent in the Input table, as indicated in the ExpectedValue field. This could be considered equivalent: Count(InputId in Input table) = ExpectedValue for Conditional's InputId .
Some examples:
Conditional (InputId = 11, ExpectedValue = 1) -> True if InputId 11 in Input Table Conditional (InputId = 12, ExpectedValue = 0) -> True if Inputid 12 NOT in Input Table
My goal
I want to get all Prizes where at least one Rule is "true". I would agree: "All Rules that are true."
My attempt
select p.PrizeId from Prize p INNER JOIN RulePrize_Map rpm ON rpm.PrizeId = p.PrizeId WHERE p.PrizeId IN (select r.PrizeId from Rule r where (select count(*) from Conditional c1 where c1.RuleId = r.RuleId) = (select count(*) from Conditional c2 where c2.RuleId = r.RuleId AND (select count(*) from Input i where i.InputId = c2.InputId) = c2.ExpectedValue ) ) GROUP BY p.prizeId
source share