2012-02-16 69 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' 
     ) 
    )