sql - How to change only first string of multiple same value on mysql row -


i have mysql query replace string on row below;

update users  set user_online = user_online - 1,     connectedsrv= case when connectedsrv= '1.1.1.1'                                               replace (connectedsrv, '1.1.1.1', '')                         else replace(connectedsrv, ';1.1.1.1', '')                     end  username='$common_name' 

however, may use same value multiple times in row ;

1.1.1.1;1.1.1.1;1.1.1.1 

once tried execute update sentence , replaces '1.1.1.1' values want delete one. result should be;

1.1.1.1;1.1.1.1 

thanks in advance,

correct way:

normalize schema , ensure every column contains atomic data (first normal form).

csv column violation of simple rule. should avoid it.


workaround way

use simple string manipulation:

update users  set user_online = user_online - 1,    connectedsrv=     case when connectedsrv= '1.1.1.1' ''      when connectedsrv '%1.1.1.1;%'           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 '%;1.1.1.1%'           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 -- 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                         ║ ╚═════════════════════════════════════════╩═══════════╩══════════════╩═════════════════════════════════╝ 

Comments

Popular posts from this blog

c++ - llvm function pass ReplaceInstWithInst malloc -

java.lang.NoClassDefFoundError When Creating New Android Project -

Decoding a Python 2 `tempfile` with python-future -