Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using CASE for an optional predicate

Tags:

sql

Can someone help me with this query?

I am new to using CASE, how can I make this work. If rights = manager then I want to run the code within the case.

select email, user_id, first_name, last_name, rights
from users u
where company_id = 2141
    and receives_emails = 'y'
    case u.rights when 'manager' then
        and user_id in (select user_id from manager_depts where company_id = u.company_id and dept_id = 2)
    end

Thanks!

like image 742
RandyLahey Avatar asked Oct 08 '22 15:10

RandyLahey


1 Answers

You actually do not need a CASE here,

SELECT email, u.user_id, first_name, last_name, rights
FROM users u
     LEFT JOIN manager_depts d ON d.company_id = u.company_id and d.dept_id = 2
WHERE company_id = 2141 AND receives_emails = 'y'
  AND (u.rights != 'manager' OR d.user_id IS NOT NULL)
like image 142
Bassam Mehanni Avatar answered Oct 12 '22 08:10

Bassam Mehanni