我有3个表来管理用户的权利
Employee
+-----------+------+
|EmployeeID | Name |
+-----------+------+
|1 |Tim |
|2 |Tom |
+-----------+------+
Right
+-----------+------+
|RightID |Name |
+-----------+------+
|1 |Read |
|2 |Write |
|3 |Change|
+-----------+------+
EmployeeRight
+-----------+--------+
|EmplyeeID | RightID|
+-----------+--------+
|1 |1 |
|1 |2 |
|2 |1 |
+-----------+--------+
现在我需要为所有用户提供正确的"更改"哪个有权"写"。但已经拥有该权利的用户不应该两次获得它。
我目前的尝试不起作用:
INSERT INTO EmployeeRight
(SELECT '3', EmployeeID FROM EmployeeRight WHERE RightID = 2 AND RightID !=3)
答案 0 :(得分:1)
使用以下脚本。
INSERT INTO Employee-Right
SELECT EmployeeID,3
FROM Employyee E
WHERE EXISTS (SELECT 1
FROM Employee-Right ER WHERE E.EmployeeID=ER.EmployeeID AND ER.Right=2 )
AND NOT EXISTS (SELECT 1
FROM Employee-Right ER WHERE E.EmployeeID=ER.EmployeeID AND ER.Right=3 )
或者您可以直接从Employee-right
表
INSERT INTO Employee-Right
SELECT DISTINCT EmployeeID,3
FROM Employee-Right ER
WHERE ER.Right=2
AND NOT EXISTS (SELECT 1
FROM Employee-Right ER1 WHERE ER.EmployeeID=ER1.EmployeeID AND ER.Right=3 )
答案 1 :(得分:1)
在单行中RightID
不能同时为2
和<>2
,您需要这样的查询:
INSERT INTO EmployeeRight
SELECT EmployeeID, 3
FROM EmployeeRight
WHERE RightID = 2 -- existing right 2
AND EmployeeID NOT IN
(
SELECT EmployeeID
FROM EmployeeRight
WHERE RightID = 3 -- but not those who already have right 3
)
答案 2 :(得分:0)
尝试以下查询
INSERT INTO EmployeeRight
select E.EmployeeID,'3' as RightID from Employee E
left join EmployeeRight ER on ER.EmplyeeID = E.EmployeeID
left join Right r on r.RightID=ER.RightID
where er.RightID = 2 and er.RightID != 3