简体   繁体   中英

Conditional sql WHERE clause based on column values

I have a table that stores users. Every user has an ID , a Name and an Access Level . The three possible Access Levels are Administrator , Manager and Simple User .

What I want is to conditionally select from this table based on the Access Level value. I demonstrate the logic bellow:

  1. If user is Administrator , then select all users ( Administrators, Managers, Simple Users )
  2. Else if user is Manager select all Managers and all Simple Users
  3. Else if user is Simple User select only himself

Is that possible?

Providing Access Level is an integer that increases with the actual access level: Administrator = 3 Manager = 2 User = 1

Then

SELECT * FROM USERS
WHERE ACCESS_LEVEL <= (SELECT ACCESS_LEVEL FROM USERS WHERE ID = @ID)

And just switch the less than sign to greater than if it is opposite.

Applies to SQL-server

EDIT: To get what you want you can use something like this:

SELECT id,name FROM users where ID = @id
UNION DISTINCT
SELECT id, name from users where access_level <= 
    (select case when access_level = 1 then 0 else access_level end
    from users where id = @id)

With a query like this you will select all users at your current access_level or lower. Only exception if your access_level is 1 (eg normal user), then only your own user is selected.

In Oracle the concept is known as Row Level Security . See articles such as this or this to get you started.

您可以使用以下代码

If(access_level=='administrator'){   str query = 'select * from users';}else if(access_level=='manager'){    str query = 'select * from users where  access_level!="administrator"'; }else{   str query = 'select * from users where access_level="users"'; }

Might be a little overkill, but the following stored procedure can be used to achieve what you want:

DROP procedure IF EXISTS `listAccessibleUsers`;

DELIMITER $$
CREATE PROCEDURE `listAccessibleUsers`(IN user_id INT)
BEGIN
  DECLARE u_access_level INT;

  -- Select the user access level  
  SELECT access_level 
  FROM users
  WHERE users.id = user_id
  INTO u_access_level;

  -- Result for simple users
  IF u_access_level = 1 THEN
    SELECT id, name, access_level 
    FROM users
    WHERE users.id = user_id;
  -- Result for admistrators and managers
  ELSE
    SELECT id, name, access_level  
    FROM users
    WHERE access_level <= u_access_level;  
  END IF;
END$$

DELIMITER ;

Example calling code:

CALL listAccessibleUsers(200);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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