问题
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.
回答1:
In the other post you are mentioning, if you look at the answer with the where exists
clause you would see that in this clause a join was made between the table in your where exists clause and at least one of the tables in your main join - which you haven't done so in your first query.
Based on the queries you posted, the second one should yield you the results that you are interested in.
回答2:
where exists (
select * from entity where o.feature_id = 2086 and o.string_value is not null
) and ( o.feature_id = 2038 )
from the first select is actually suposed to be
where exists (
select * from entity where o.feature_id = 2086 and o.string_value is not null
) or ( o.feature_id = 2038 )
since you can't have a record that has the id = 2086 AND id = 2038
回答3:
In the first query server in first place search for
SELECT DISTINCT(e.id)
FROM entity AS e
JOIN organization_feature AS o
ON o.entity_id = e.id
WHERE
AND ( o.feature_id = 2038 )
and then for each founded record it executes
and EXISTS
(SELECT *
FROM entity
WHERE o.feature_id = 2086
AND o.string_value IS NOT NULL
)
in this case every record from first step has value o.feature_id = 2038 and second step is always false
来源:https://stackoverflow.com/questions/23359790/can-anyone-explain-why-this-first-sql-query-gives-0-when-this-second-query-gives