在嵌套查询中,检查条件的所有值
如何摆脱嵌套查询(同意,不同意)?如何重写加入 - 我想不出。也许还有其他最佳解决方案?
select *
from (
select
(select count(id) from Agreement a where a.ConclusionCardFile = f.id and a.Status = 1) agreed,
(select count(id) from Agreement a where a.ConclusionCardFile = f.id and (a.Status <> 1 or a.Status is null)) dis_agreed
from ConclusionCard_Files f
) t
where t.agreed > 0 and dis_agreed = 0
How can I get rid of nested queries (agree, dis_agreed)? How to rewrite to join - I can not think of it. Maybe there are other optimal solutions?
select *
from (
select
(select count(id) from Agreement a where a.ConclusionCardFile = f.id and a.Status = 1) agreed,
(select count(id) from Agreement a where a.ConclusionCardFile = f.id and (a.Status <> 1 or a.Status is null)) dis_agreed
from ConclusionCard_Files f
) t
where t.agreed > 0 and dis_agreed = 0
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以将条件编写为
where
子句:You can write the conditions as a
where
clause:也许您只是使用子查询来过滤?将它们移至 WHERE 子句怎么样?
它对性能友好,因为 SqlServer 不会计算所有计数
Maybe you just using sub-queries only to filter? What about to move them to WHERE clause?
It's performance friendly because SqlServer do not count all Counts
如果我理解正确,您可以尝试将
JOIN
与HAVING
条件聚合函数一起使用。请编辑
如果您想根据您的情况从
ConclusionCard_Files
获取数据, 。您可以尝试让子查询中的条件聚合函数来自表Agreement
的每个ConclusionCardFile
,然后执行JOIN
If I understand correctly, you can try to use
JOIN
withHAVING
condition aggregate function.EDIT
if you want to get data from
ConclusionCard_Files
based on your condition. you can try to let condition aggregate function in subquery eachConclusionCardFile
from tableAgreement
then doJOIN