douyiqi9640 2013-01-16 11:45
浏览 23

我应该如何用逗号完全删除数据库中的id?

I have a table tbl_scripts that goes like this:

 allowed_group_ids
+-----------------+
 12343,12343,21342

And I need to remove from this string a group id, for example 12343. Setting delete_group_id to 12343, the below query seems to work correctly:

UPDATE tbl_scripts
SET allowed_group_ids = 
  REPLACE(
    REPLACE(allowed_group_ids, '$delete_group_id,', ''),
    ',$delete_group_id', '')
WHERE
  system_id = {$_SESSION['system_id']}

But if the column only has a single value, it fails:

 allowed_group_ids
+-----------------+
 12343 <-----I'm not able to replace this with blank

I know I should normalize the table, but at the moment I can't change my database structure, so I'm trying to make it work this way. How can I make my query work with single values?

  • 写回答

4条回答 默认 最新

  • donglingsai2880 2013-01-16 11:53
    关注

    The first replace searches for a trailing comma, the second for a leading comma. The single group id has no trailing comma.

    Safest option is to run a second query for the case where the field = value

    doing this at any point

    REPLACE(allowed_group_ids, '$delete_group_id', '')
    

    May delete parts of longer ids (e.g. 123456 out of 1234567 would leave 7) So don't do that

    Alternatively always add a trailing comma even for single ids, then you only need something like

    REPLACE(allowed_group_ids, '$delete_group_id,', '')
    

    Adding a trailing comma, is something that you can easily update across the whole db, (as a one off query)

    UPDATE table SET allowed_group_ids = CONCAT(allowed_group_ids, ',');
    

    Then check through your code for insert and udpate statement acting on this table

    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题