-1

I have this inner query that selects all affiliates linked to the giver user.

 (SELECT 
    `realtor_user_id`
 FROM
    `affiliate_assignments`
 WHERE
 `lender_user_id` = `users`.`id`)

affiliate_assignments structure is:

id | realtor_user_id | lender_user_id

where users table is joined in outer query and both realtor_user_id and lender_user_id are foreign keys of users.id

I also have user's role (selected in outer query) that can be realtor or lender

What I need is:

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

How can achieve this?

xpuc7o
  • 333
  • 3
  • 15
  • 1
    Use CASE in place of IF. https://dev.mysql.com/doc/refman/5.7/en/case.html – Syntax Error Nov 24 '16 at 15:06
  • This is definitely not a duplicate of a question that just says the answer is `case`. Read the question . . . it involves multiple different columns and correlations. – Gordon Linoff Nov 24 '16 at 15:15

3 Answers3

2

You can use case when

    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

do the fact you have different where condition you can rebuil you condition using composite condition is when clause

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
ScaisEdge
  • 131,976
  • 10
  • 91
  • 107
0

Using case statement:

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
d345k0
  • 78
  • 1
  • 6
0

One way to approach this uses left joins:

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';
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786