我有以下查询
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%')
我如何重用in
的查询语句?我尝试了How to reuse a sub query in sql?的接受答案为
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
WHERE user_id in cte
or approver_id in cte
or second_approver_id in cte
但这不行。我怎样才能实现它?
答案 0 :(得分:2)
试试这个:
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)
)
答案 1 :(得分:1)
您可以尝试这样:
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%'))
答案 2 :(得分:0)
尝试此查询。
;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