将查询从in()重写为联接

时间:2018-07-14 16:00:32

标签: sql amazon-redshift

您能协助将其重写为联接吗?

select * from users where users.advised_by in (
select p.id 
from advisors p
join advisor_members m on p.id = m.advisor_id
join representatives r on m.user_id=r.user_id
where m.memeber_type='Advisor'
)

这是200多个行查询的一部分,并且在进行更改时in()语句很难维护。

2 个答案:

答案 0 :(得分:2)

您应该使用适当的on子句

select * 
from users 
inner join 
(
select p.id 
from advisors p
join advisor_members m on p.id = m.advisor_id
join representatives r on m.user_id=r.user_id
where m.memeber_type='Advisor'
) t on users.advised_by  = t.id

答案 1 :(得分:0)

/ *选项1 * /

选择* FROM用户usr 内部联接            (                   SELECT p.id AS advisor_id                   来自顾问p                   JOIN advisor_members m                   开p.id = m.advisor_id                   加入代表                   开启m.user_id = r.user_id                   m.memeber_type ='Advisor')T2 usr.advised_by = t2.advisor_id

/ *选项2-* / 选择 * FROM用户usr INNER JOIN顾问p 在usr.advised_by = p.id上 加入            (                   选择 *                   来自advisor_members                   在哪里m.memeber_type ='Advisor')m 开p.id = m.advisor_id 加入代表 开启m.user_id = r.user_id