简体   繁体   English

更新行而不删除mysql中的先前值

[英]update row without deleting previous values in mysql

One of my table has a field user_ids and the value of the field like 2,3 我的一张桌子有一个字段user_ids和该字段的值,例如2,3

group_id| user_ids  
--------|------------   
1       | 2,3  
--------|------------  
2       | 5,8

I want to update the field without deleting the current value. 我想更新该字段而不删除当前值。 For ex. 对于前。 If I need to add 5 for group_id id 1, then 2,3 should be like 2,3,5 如果我需要为group_id id 1添加5,那么2,3应该像2,3,5

I m using this query: 我正在使用此查询:

UPDATE users_group SET user_ids = CONCAT( SUBSTRING( user_ids, 1, CHAR_LENGTH( user_ids ) -1 ) , ',5' ) WHERE group_id =1

But it is deleting previous value with comma. 但是它将用逗号删除先前的值。

group_id| user_ids  
--------|------------   
1       | ,5  
--------|------------  
2       | 5,8

can anyone suggest the right way for this? 有人可以为此建议正确的方法吗?

Can you not just concatenate it on, rather than trying to split it up first? 您不仅可以将其连接起来,还可以尝试先将其拆分吗?

UPDATE users_group 
SET user_ids = CONCAT_WS(',', user_ids, '5' ) 
WHERE group_id =1

But this does suggest a badly normalised database design. 但是,这确实表明数据库设计标准化很差。 Generally a comma separated list should instead be stored as rows on another table (ie, one row per value in the list) as suggested by Mark Baker. 通常,用逗号分隔的列表应该作为行存储在另一张表上(如列表中每个值一行),如Mark Ba​​ker所建议的那样。

EDIT - If you want to only have a single copy of any id in each user_ids field, irrespective of how many times you try to insert it, and you want to be able to add multiple ids at once:- 编辑-如果您想在每个user_ids字段中仅包含任何ID的单个副本,而无论您尝试插入多少次,并且希望一次添加多个ID:-

UPDATE users_group a
INNER JOIN
(
    SELECT 3 AS an_id
    UNION 
    SELECT 4
) b
ON FIND_IN_SET(b.an_id, a.user_ids) = 0
SET a.user_ids = CONCAT_WS(',', a.user_ids, b.an_id ) 
WHERE a.group_id =1

EDIT again - if you have a table of users containing the ids then you can select the ids from that where the id is one of those you want to add. 再次编辑-如果您有一个包含ID的用户表,则可以从ID中选择要添加的ID的ID中进行选择。

Something like this. 这样的事情。

UPDATE users_group a
INNER JOIN
(
    SELECT id
    FROM users
    WHERE id IN (3, 4)
) b
ON FIND_IN_SET(b.id, a.user_ids) = 0
SET a.user_ids = CONCAT_WS(',', a.user_ids, b.id ) 
WHERE a.group_id =1
update table1 set name = concat(name, ', ', 5) WHERE group_id =1

Please try this query. 请尝试此查询。 It may be useful for you. 这可能对您有用。

UPDATE users_group SET user_ids = CONCAT( user_ids , ',5' ) WHERE group_id =1

Try the below query: 请尝试以下查询:

UPDATE users_group 
SET user_ids = CONCAT( user_ids , ',5' ) 
WHERE group_id =1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM