2012-02-16 10 views
5

Czy ktoś może mi pomóc w tym zapytaniu?Używanie CASE dla opcjonalnego predykatu

Jestem nowy w używaniu CASE, jak mogę to zrobić. Jeśli rights = manager, to chcę uruchomić kod w tej sprawie.

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 

Dzięki!

+0

Co RDBMS używasz? – Dan

+0

Czy próbujesz sprawdzić, czy użytkownik jest menedżerem, czy chcesz je tylko zwrócić, jeśli jest menedżerem? Nie jest to język imperatywny - nie można (zazwyczaj) modyfikować tabeli z klauzuli "WHERE". –

Odpowiedz

5

rzeczywiście nie potrzebują sprawie,

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) 
+0

To idealne, dzięki! – RandyLahey

+0

@RandyLahey Cieszę się, że mogę pomóc! –

-1

napisać go w ten sposób

select 
    email, user_id, first_name, last_name, rights 
from 
    users u 
where 
    company_id = 2141 
    and 
    receives_emails = 'y' 
    and 
    (
     (
      u.rights = 'manager' 
      and 
      user_id in (
        select 
         user_id 
        from 
         manager_depts 
        where 
         company_id = u.company_id 
         and 
         dept_id = 2 
       ) 
     ) 
     or 
     (
      u.rights <> 'manager' 
     ) 
    ) 
Powiązane problemy