以下是我的表格,
1)角色
roleId roleName
1 Super Admin
2 State Licensee
3 County Licensee
4 Vendor Licensee
5 Driver Licensee
2)权限
permissionId permissionActivity
1 Add SL
2 Add CL
3 Add VL
4 Add DL
5 Validate SL
6 Validate CL
3)RolePermissionDetails
roleId permissionId
1 1
1 2
1 3
1 4
1 5
1 6
1 7
2 2
2 3
2 8
这里我想一次更新第二个roleId的所有permissionId,如下所示: -
2 -> 3
2 -> 4
2 -> 5.
这样做的正确方法应该是什么。
答案 0 :(得分:0)
您可以更新如下: -
UPDATE ROLE_PERMISSION_DETAILS SET PERMISSION_ID=3 WHERE PERMISSION_ID=2 AND ROLE_ID=2;
UPDATE ROLE_PERMISSION_DETAILS SET PERMISSION_ID=4 WHERE PERMISSION_ID=3 AND ROLE_ID=2;
UPDATE ROLE_PERMISSION_DETAILS SET PERMISSION_ID=5 WHERE PERMISSION_ID=8 AND ROLE_ID=2;
通过在where子句之后添加条件,可以为任意数量的行创建更新,甚至可以为更复杂的条件创建更新。
或者在查询中使用if和case是否合适
UPDATE ROLE_PERMISSION_DETAILS SET
PERMISSION_ID = IF(PERMISSION_ID=2,3,PERMISSION_ID),
PERMISSION_ID = IF(PERMISSION_ID=4,5,PERMISSION_ID),
PERMISSION_ID = IF(PERMISSION_ID=5,8,PERMISSION_ID)
WHERE PERMISSION_ID= 2
或
UPDATE ROLE_PERMISSION_DETAILS SET
PERMISSION_ID = CASE WHEN PERMISSION_ID=2 THEN 3 ELSE PERMISSION_ID),
PERMISSION_ID = CASE WHEN PERMISSION_ID=4 THEN 5 ELSE PERMISSION_ID),
PERMISSION_ID = CASE WHEN PERMISSION_ID=5 THEN 8 ELSE PERMISSION_ID) WHERE PERMISSION_ID= 2