Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL: Loop through one table and update another?

Table t1:

s (string)      |  x (int)
----------------+--------
"gfrdgeradfg"   |  0
"abdfodpnmn"    |  0
...             |  ...

Table t2:

c (varchar(1))
-----
"a"  
"c"  
"g"
"r"  
-----

I would like to add +1 to t1.x for every character t2.c that occurs in t1.s, i.e. the result should be something like this:

s               |  x
----------------+--------
"gfrdgeradfg"   |  3      (contains "a","g","r")
"abdfodpnmn"    |  1      (contains "a")
...             |  ...

Looping through t2 and update t1 in php is quite straightforward, but I'd rather do it in pure SQL, if possible.

Thanks for your help.

like image 953
ajo Avatar asked May 24 '26 12:05

ajo


1 Answers

UPDATE t1
SET x = (
    SELECT SUM(t1.s LIKE CONCAT('%', t2.c, '%'))
    FROM t2
)

Clarification: The expression t1.s LIKE CONCAT('%', t2.c, '%') will evaluate to a Boolean which is equivalent to 1 or 0 in MySQL.

I didn't test it so please tell me if it doesn't work.

like image 118
Alin Purcaru Avatar answered May 26 '26 03:05

Alin Purcaru



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!