gpt4 book ai didi

mysql - 如何仅更改mysql行上多个相同值的第一个字符串

转载 作者:行者123 更新时间:2023-11-29 02:51:49 25 4
gpt4 key购买 nike

我有一个 mysql 查询来替换一行中的字符串,如下所示;

UPDATE users 
SET user_online = user_online - 1,
connectedSRV= case when connectedSRV= '1.1.1.1' then
REPLACE (connectedSRV, '1.1.1.1', '')
else REPLACE(connectedSRV, ';1.1.1.1', '')
end
WHERE username='$common_name'

但是,我可能会在行中多次使用相同的值;

1.1.1.1;1.1.1.1;1.1.1.1

一旦我尝试执行更新语句,它会替换所有“1.1.1.1”值,但我只想删除一个。所以结果应该是;

1.1.1.1;1.1.1.1

提前致谢

最佳答案

正确方法:

规范化您的模式并确保每一列都包含原子数据(第一范式)。

CSV 列违反了这个简单的规则。你应该避免它。


解决方法

使用简单的字符串操作:

UPDATE users 
SET user_online = user_online - 1,
connectedSRV=
CASE WHEN connectedSRV= '1.1.1.1' then ''
WHEN connectedSRV LIKE '%1.1.1.1;%' THEN
concat(left(connectedSRV, instr(connectedSRV,'1.1.1.1;')-1),
substr(connectedSRV, instr(connectedSRV,'1.1.1.1;')+ length('1.1.1.1;')))
WHEN connectedSRV LIKE '%;1.1.1.1%' THEN
concat(left(connectedSRV, instr(connectedSRV,';1.1.1.1')-1),
substr(connectedSRV, instr(connectedSRV,';1.1.1.1')+ length(';1.1.1.1')))
ELSE connectedSRV
END
-- WHERE username='$common_name'

SqlFiddleDemo

╔═════════════════════════════════════════╦═══════════╦══════════════╦═════════════════════════════════╗
║ initial ║ username ║ user_online ║ connectedSRV ║
╠═════════════════════════════════════════╬═══════════╬══════════════╬═════════════════════════════════╣
║ 1.1.1.1;1.1.1.1;1.1.1.1 ║ aaa ║ 9 ║ 1.1.1.1;1.1.1.1 ║
║ 1.1.1.1 ║ aab ║ 7 ║ ║
║ 1.1.1.1;2.1.1.1 ║ aac ║ 7 ║ 2.1.1.1 ║
║ 3.1.1.1;1.1.1.1 ║ aad ║ 6 ║ 3.1.1.1 ║
║ 4.1.1.1;1.1.1.1;3.1.1.1;1.1.1.1;1.1.1.1 ║ aae ║ 4 ║ 4.1.1.1;3.1.1.1;1.1.1.1;1.1.1.1 ║
║ 1.2.3.4 ║ aaf ║ 3 ║ 1.2.3.4 ║
╚═════════════════════════════════════════╩═══════════╩══════════════╩═════════════════════════════════╝

关于mysql - 如何仅更改mysql行上多个相同值的第一个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34828488/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com