Update a database field has a value string concatenation

When we develop systems involving authority, we will deal with the relationship between users and roles

Under normal circumstances, we will build a user role relational mapping table: user_role_mapping

Field has id, user_id, role_id

If a user has multiple roles, then user_role_mapping table is a number of records

There is also a special treatment

Role_ids a new field in the user record in the user table

If a user has multiple roles, then the value is recorded in role_ids 1, a plurality of characters separated by a comma

How to add a new batch that we roles to users (the users in an organization) time to deal with it?

Put simply divided into three cases:

1. The new role if the user already exists, this time do not need to be modified, we maintain that a number of the same user rights

2. If you have never set characters (null), or the role of the field is empty, we add to this group of users permission directly: set role_ids = new role_id

3. If you set too many roles (Note To troubleshoot situations include new roles), such as the role of the user 666666 on the map are 9 and 10, we add to his role 11, the value of the latest role_ids is 9,10, 11, we need to set role_ids = concat (role_id, '', 'new role_id') to

Summing up the appeal statement is as follows

UPDATE user set role_ids = 新role_id WHERE dept_id IN ('deptid1','deptid2') AND (role_ids  = '' OR role_ids is null);
UPDATE user set role_ids = 新role_id WHERE dept_id IN ('deptid1','deptid2') AND LENGTH(role_ids ) > 0 AND LOCATE(新role_id,role_ids ) = 0;
Explain the LOCATE (new role_id, role_ids) = 0 

returns the new location string field role_ids role_id first appears, where 0 is not found, the user indicates a plurality of characters does not include a new role

bulk edits when you need to perform more than two statements.

 

Guess you like

Origin www.cnblogs.com/liuxiutianxia/p/11209803.html