我有一个包含用户和任务的表。有50个任务和大约1000个用户。用户或者完全有权访问任务,或者没有访问权。我想向该表添加一个新任务,并需要一个查询,该查询将检查用户是否已经有权访问该任务(完全或无),如果没有,则向该用户添加任务并授予访问权限。示例行:ID(2) USER(Bob) TASK(Clean) ACCESS(Yes)
。
这是我认为可以使用的SQL。我即将完成这项工作吗?
INSERT INTO table (DEPT, ID, USER, TASK, ACCESS)
SELECT DEPT, ID, USER, 'New Task','Yes',
FROM table
WHERE NOT EXISTS (
SELECT 1 FROM table WHERE task = 'New Task');
答案 0 :(得分:0)
您可以在接近时使用NOT EXISTS
子句或NOT IN
子句来实现它:
INSERT INTO table
(dept,
id,
USER,
task,
access)
SELECT dept,
id,
USER,
'New Task',
'Yes',
FROM table t1
WHERE USER NOT IN(SELECT USER
FROM table t2
WHERE task = 'New Task' AND access = 'YES');
INSERT INTO table
(dept,
id,
USER,
task,
access)
SELECT dept,
id,
USER,
'New Task',
'Yes',
FROM table t1
WHERE NOT EXISTS (SELECT 1
FROM table t2
WHERE task = 'New Task' AND access = 'YES' and t2.USER = t1.USER);