我有这个内部查询,选择链接到给予者用户的所有分支机构。
(SELECT
`realtor_user_id`
FROM
`affiliate_assignments`
WHERE
`lender_user_id` = `users`.`id`)
affiliate_assignments
结构是:
id | realtor_user_id | lender_user_id
其中users
表在外部查询中加入,realtor_user_id
和lender_user_id
都是users.id
的外键
我还有用户的role
(在外部查询中选择),可以是realtor
或lender
我需要的是:
IF role = 'lender'
SELECT realtor_user_id
FROM affiliate_assignments
WHERE lender_user_id = users.id
ELSE IF role = 'realtor'
SELECT lender_user_id
FROM affiliate_assignments
WHERE realtor_user_id = users.id
END IF
如何实现这一目标?
答案 0 :(得分:2)
时可以使用案例
select case when role = 'lender' then realtor_user_id
when role = 'realtor' then lender_user_id
end as my_result
FROM affiliate_assignments
WHERE lender_user_id = users.id
事实上你有不同的条件你可以使用复合条件重建你的条件是when子句
select case
when role = 'lender' AND lender_user_id = users.id then realtor_user_id
when role = 'realtor' AND realtor_user_id = users.id then lender_user_id
ELSE your_result_for else
FROM affiliate_assignments
答案 1 :(得分:0)
使用案例陈述:
SELECT CASE
WHEN role = 'lender' THEN realtor_user_id
WHEN role = 'realtor' THEN lender_user_id
END CASE
FROM affiliate_assignments
WHERE realtor_user_id = users.id
答案 2 :(得分:0)
解决此问题的一种方法是使用left join
s:
select u.*,
coalesce(aal.realtor_user_id, aar.lender_user_id) as other_user_id
from users u left join
affiliate_assignments aal
on u.id = aal.lender_user_id and u.role = 'lender' left join
affiliate_assignments aar
on u.id = aar.realtor_user_id and u.role = 'realtor';