简体   繁体   中英

MySQL, apply a function on one column and then update another column for each row

Two of a table's columns are named csv and s. csv contains comma separated 1 digit numbers as a string, no duplication, like '1,5,3,2', there is no duplication like '1,5,1'. Want to count how many 1s and 3s there are in 'csv' and put the count into column 's'. It's like to apply a function to each 'csv' and put the result into 's' for each row. I know how to count, but had never seen how to apply a function to one column and put result into another column. This is done in stored procedure, do I have to go through it row by row.

Just:

update mytable 
set s = char_length(csv) - char_length(replace(replace(csv, '1', ''), '3', ''))

The formula compares the number of characters in column csv to the number of characters after removing 1 s and 3 s.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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