我有两个 SQL 查询,我认为它们应该是等价的:
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
这是第一个,这是第二个:
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
问题是第一个给我 0 作为计数结果,而第二个给我 13411。有关我的数据库结构的更多信息或更好地理解查询 see here (如果人们希望我在这里重新发布信息,我很乐意)。
谁能解释为什么它们不等价并提供一个我可以使用的“where exists”子句?
编辑:感谢大家的帮助,感谢您的建议,我意识到我应该使用:
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
完成我想做的事情。因为我需要连接第三个变量来完成我正在尝试的查询,所以这提供了一个与我正在尝试的 query_2 相同的解决方案。再次感谢大家。
最佳答案
在您提到的另一篇文章中,如果您查看带有 where exists
子句的答案,您会看到在该子句中 a join was made between the table in your where exists子句和主连接中的至少一个表 - 您在第一个查询中没有这样做。
根据您发布的查询,第二个应该会产生您感兴趣的结果。
关于mysql - 谁能解释为什么当第二个查询给出结果时第一个 SQL 查询给出 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23359790/