简体   繁体   English

MySQL if条件在where子句查询中

[英]MySQL If condition in where clause query

I have a table as below and a USR table which shows is a user is admin or a regular user. 我有一个下表和一个USR表,该表显示用户是admin还是普通用户。 In this case USR_ID: 1 is as admin 在这种情况下,USR_ID:1以管理员身份

EMP_ID     Terminated    EMP_Name      EMP_Loc
  1         0            John         Caster
  2         1            Sally        Jules
  3         0            Steven        James

This is a EMP db table and EMP#2 is terminated and when a regular user queries the DB, the terminated Employee's should not be shown and while an admin queries the DB, i would like to show all the employee's including the terminated ones. 这是一个EMP数据库表,EMP#2已终止,当普通用户查询数据库时,不应显示已终止的雇员,而在管理员查询数据库时,我想显示所有雇员,包括已终止的雇员。

Here is my query 这是我的查询

 select * from EMP join USR on USR.ID = EMP.EMP_ID
 where (IF USR.ID = '1',terminated='1',terminated in ('0','1')) 

but this query only show non-terminated users always even for admin user 但是此查询始终仅显示未终止的用户,即使对于管理员用户

You can just use OR in your where condition, something like 您可以在您的where条件中使用OR,例如

select * from EMP join USR on USR.ID = EMP.EMP_ID
where (USR.ID = '1' and terminated='1') or (USR.ID <> '1' and terminated in ('0','1')) 
SELECT * 
FROM   EMP 
       INNER JOIN USR ON USR.ID = EMP.EMP_ID
WHERE
       (USR.ID = '1' AND Terminaded = '1') OR (USR.ID <> '1')

As your requirement, you can try this: 根据您的要求,您可以尝试以下操作:

select * 
from EMP join USR on USR.ID = EMP.EMP_ID
where (USR.ID <> '1' and Terminated = '1') or (Terminated in ('0', '1'))

if Terminated only have two value '0' or '1', you can remove or clause: 如果Terminated只有两个值'0'或'1',则可以删除or子句:

select * 
from EMP join USR on USR.ID = EMP.EMP_ID
where (USR.ID <> '1' and Terminated = '1')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM