更新链接表

时间:2019-05-24 15:49:09

标签: mysql sql

我正在从社区中验证以下SQL方法,在该社区中我将完全更新用户的角色。 (完整更新联接表)

用户

+----+-------+------+
| id | first | last |
+----+-------+------+
|  1 | John  | Doe  |
|  2 | Jane  | Doe  |
+----+-------+------+

角色

+----+----------+
| id |   name   |
+----+----------+
|  1 | admin    |
|  2 | accounts |
|  3 | sales    |
+----+----------+

UserRole

+--------+--------+
| userid | roleid |
+--------+--------+
|      1 |      1 |
|      1 |      2 |
|      1 |      3 |
|      2 |      2 |
|      2 |      3 |
+--------+--------+

我的SQL方法->首先删除所有记录,然后插入所有记录

DELETE FROM UserRole WHERE userid = 1;
INSERT INTO UserRole(userid, roleid) VALUES(1, 2), (1, 3);

有更好的方法吗?我的意思是可能在单个查询中针对这些类型的链接/联接表执行此操作?

修改

我认为应该找到有效的SQL操作而不是单个查询。

这是另一个SQL

DELETE FROM UserRole WHERE user_id = 1 AND role_id NOT IN (2, 3);
INSERT INTO UserRole(user_id, role_id) VALUES(1, 2), (1, 3)
ON DUPLICATE KEY UPDATE user_id = VALUES(user_id), role_id = VALUES(role_id);

1 个答案:

答案 0 :(得分:0)

如果要将所有用户的所有角色添加到userRoles表中,则可以从userRoles中删除,然后重新创建表,如下所示:

var root = JObject.Parse(json);
var sub = root["mainProperty"][0]["entries"][2]["entries"][0];
debugOutput((string)sub);

输出:

DECLARE @users TABLE ( userID INT, UserName NVARCHAR(MAX) )
DECLARE @roles TABLE ( roleID INT, RoleName NVARCHAR(MAX) )
DECLARE @userRoles TABLE ( userID INT, roleID INT )

INSERT INTO @users (userID,UserName) VALUES (1,'name1'),(2,'name2'),(3,'name3')
INSERT INTO @roles (roleID,RoleName) VALUES (1,'admin'),(2,'accounts'),(3,'sales')

INSERT INTO @userRoles (userID,roleID)
SELECT U.userID,R.roleID FROM @users U
FULL OUTER JOIN @roles R ON 1=1
ORDER BY userID

SELECT * FROM @userRoles