0

How would I 'add' data to a field if it doesn't exist?

Let's say I have 4 rows. And a column, say "datafield" looks like this:

        datafield
row001: |a|
row002: |b||c|
row003: |b||d|
row004: 

How would I create a mySQL query, such that it "adds" the value "|b|" if it doesn't exist in the row? (Not 'replacing' the data, but rather 'adding' to it).

So both row001 & row004 would get "|b|" added to them, but row001 would now contain both "|a||b|" and row004 would now be "|b|"?

So it would look like this?

        datafield
row001: |a||b|
row002: |b||c|
row003: |b||d|
row004: |b|
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
user6262902
  • 129
  • 9
  • Please read https://stackoverflow.com/questions/3653462/is-storing-a-delimited-list-in-a-database-column-really-that-bad – Nick Nov 11 '19 at 02:44

2 Answers2

1

Is this what you want?

update mytable
set datafield = concat(coalsece(datafield, ''), '|b|')
where datafield is null or datafield not like '%|b|%'

This phrases as: if datafield is null or doesn't contain '|b|', append '|b|' to datafield.

GMB
  • 216,147
  • 25
  • 84
  • 135
0

you can use locate() function to check if |b| existed

update tableA
set datafield = concat(coalesce(datafield, ''), '|b|')
where locate('|b|', coalesce(datafield, '')) = 0
Ed Bangga
  • 12,879
  • 4
  • 16
  • 30