如何重用IN子查询的查询?
Posted
技术标签:
【中文标题】如何重用IN子查询的查询?【英文标题】:How to reuse query of IN sub query? 【发布时间】:2016-09-13 05:27:10 【问题描述】:我有以下查询
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
但这不行。我怎样才能实现它?
【问题讨论】:
【参考方案1】:试试这个:
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)
)
【讨论】:
谢谢先生。这就是我要找的。span> 【参考方案2】:你可以这样试试:
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%'))
【讨论】:
【参考方案3】:试试这个查询。
;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
【讨论】:
我得到了重复的结果。以上是关于如何重用IN子查询的查询?的主要内容,如果未能解决你的问题,请参考以下文章