2012-02-16 70 views
5

有人可以幫助我處理此查詢嗎?使用CASE作爲可選謂詞

我是使用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 

謝謝!

+0

您正在使用什麼RDBMS? – Dan 2012-02-16 22:51:45

+0

您是否試圖查看用戶是經理,還是隻想回到他們,如果他們是經理?這不是一種命令式語言 - 你不能(通常)從'WHERE'子句中修改一個表。 – 2012-02-16 22:52:07

回答

5

你其實並不需要在此情況下,

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

這很完美,謝謝! – RandyLahey 2012-02-16 22:55:32

+0

@RandyLahey很高興能幫到你! – 2012-02-16 22:58:22

-1

寫這樣

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' 
     ) 
    )