I have two SQL queries that I thought should be equivalent:
SELECT COUNT(*) FROM (
SELECT distinct(e.id) FROM entity as e
join organization_feature as o on o.entity_id = e.id
where exists (
select * from entity where o.feature_id = 2086 and o.string_value is not null
) and ( o.feature_id = 2038 ) GROUP BY e.id
) as res
This is the first one and here is the second:
SELECT COUNT(*) FROM (
SELECT distinct(e.id) FROM entity as e
join organization_feature as o on o.entity_id = e.id
where ( o.feature_id = 2038 )
or (o.feature_id = 2086 and o.string_value is not null)
GROUP BY e.id having count(*)=2
) as res
The problem is that the first gives me 0 as the count results while the second one gives me 13411. For more information on the structure of my database or to better understand the queries see here (if people would like me to repost the information here I'm happy to).
Can anyone explain why they are not equivalent and provide a "where exists" clause that I will be able to use?
EDIT: Thank you everyone for your help, thanks to your advice I realised that I should be using:
SELECT COUNT(*) FROM (
SELECT distinct(e.id) FROM entity as e
join organization_feature as o on o.entity_id = e.id
where exists (
select * from organization_feature as of where of.feature_id = 2086 and of.string_value is not null and of.entity_id = e.id
) and ( o.feature_id = 2038 ) GROUP BY e.id
) as res
to accomplish what I was trying to do. as I needed a third variable of to be joined to accomplish the query I was attempting, this provides a solution that is identical to query_2 as I was trying. Thank you again everyone.