Sql 如何在子查询中重用查询?
我有以下疑问Sql 如何在子查询中重用查询?,sql,sql-server,Sql,Sql Server,我有以下疑问 select a.id, a.user_id, a.approver_id, a.second_approver_id from tbl_approve_master a WHERE user_id in (select id from tbl_user where name like '%john%') or approver_id in (select id from tbl_user where name like '%john%') or second_approve
select a.id, a.user_id, a.approver_id, a.second_approver_id
from tbl_approve_master a
WHERE user_id in (select id from tbl_user where name like '%john%')
or approver_id in (select id from tbl_user where name like '%john%')
or second_approver_id in (select id from tbl_user where name like '%john%')
如何在中重用的查询语句?我试着接受as的答案
但这不好。我怎样才能做到这一点?试试这个:
select a.id, a.user_id, a.approver_id, a.second_approver_id
from tbl_approve_master a
WHERE exists (
select *
from tbl_user u
where u.name like '%john%'
and u.id in (a.user_id, a.approver_id, a.second_approver_id)
)
尝试此查询
;with cte as (select id from tbl_user where name like '%john%')
select a.id, a.user_id, a.approver_id, a.second_approver_id
from tbl_approve_master a
join cte
on user_id = cte.id or approver_id = cte.id or second_approver_id = cte.id
您可以这样尝试:
select a.id, a.user_id, a.approver_id, a.second_approver_id
from tbl_approve_master a
where exists (select 1 from tbl_user at
where (a.user_id = at.id
or a.approver_id = at.id
or a.second_approver_id =id)
and (at.name like '%john%'))
我得到了重复的结果。谢谢你,先生。这就是我要找的。
select a.id, a.user_id, a.approver_id, a.second_approver_id
from tbl_approve_master a
where exists (select 1 from tbl_user at
where (a.user_id = at.id
or a.approver_id = at.id
or a.second_approver_id =id)
and (at.name like '%john%'))