-- 用户表CREATE TABLE users (
user_id INT PRIMARY KEY,
username VARCHAR(255),
role_id INT,
department_id INT);
-- 角色表CREATE TABLE roles (
role_id INT PRIMARY KEY,
role_name VARCHAR(255)
);
-- 数据表CREATE TABLE data (
data_id INT PRIMARY KEY,
data_value VARCHAR(255),
department_id INT);
INSERT INTO roles (role_id, role_name)
VALUES(1, '普通角色'),
(2, '部门领导'),
(3, '高层');
INSERT INTO users (user_id, username, role_id, department_id)
VALUES(1, '普通用户1', 1, 101),
(2, '普通用户2', 1, 102),
(3, '部门领导1', 2, 101),
(4, '部门领导2', 2, 102),
(5, '高层用户', 3, NULL);
INSERT INTO data (data_id, data_value, department_id)
VALUES(1, '数据1', 101),
(2, '数据2', 101),
(3, '数据3', 102),
(4, '数据4', 102),
(5, '数据5', NULL);
-- 普通角色只能查看自己的数据
SELECT data_id, data_value FROM data
WHERE department_id = (SELECT department_id FROM users WHERE user_id = 1);
-- 部门领导可以看自己部门数据
SELECT data_id, data_value FROM data
WHERE department_id = (SELECT department_id FROM users WHERE user_id = 3) OR department_id IS NULL;
-- 高层可以看整个数据
SELECT data_id, data_value FROM data;