问题
how to grant a read privilege to all information included in a view DRVADM except the rows where a date of birth is not empty to a user?
回答1:
Consider the following:
drop table if exists variousRights;
create table variousRights
( -- whitelist table of various privileges
id int auto_increment primary key,
rightType varchar(100) not null,
username varchar(100) not null
);
-- sample data below. For this exercise, all we care about is 'seeNullBirthDateRows'
-- but other data is inserted to ferret out troubles with strategy (too many rows returned)
insert variousRights (rightType,userName) values
('seeNullBirthDateRows','root@localhost'),
('seeNullBirthDateRows','sam@localhost'),
('seeSecretIDs','root@localhost'),
('insertThing101','root@localhost');
drop table if exists employees;
create table employees
( id int auto_increment primary key,
empName varchar(100) not null,
birthDate date null
);
-- sample data inserted. One has a null for birthDate (empty as you say in the question)
insert employees(empName,birthDate) values
('John Smith',null),
('Sally Higgins','2016-02-07'),
('John Smith','2010-01-27');
The query:
select id,empName,birthDate
from employees
where birthDate is not null
union
select e.id,e.empName,e.birthDate
from employees e
cross join (select id from variousRights where rightType='seeNullBirthDateRows' and userName=current_user()) vr
where e.birthDate is null;
The query relies on a Cross Join and a union. As for the union, the first part will be the same for all users: all rows from employees
with a non-null birthDay. The second part of the union will return the nulls for users so privileged in the variousRights
table where you dream up your privileges.
Naturally the above query can be plopped into a view.
See the mysql manual page for the CURRENT_USER() function.
As for the cross join
, think of it this way. It is a cartesian product. But the table joined on (alias vr
) will either have 1 row or 0 coming back. That is what determines whether or not privileged users see the null birthDate rows.
Note: The above has been tested. Seems to work fine.
来源:https://stackoverflow.com/questions/37494907/grant-select-privilege-to-rows-with-condition