MySQL: Go through one table and upgrade 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 t2.c character 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")
...             |  ...

Quoting via t2 and updating t1 in php is pretty simple, but I would rather do it in pure SQL, if possible.

Thank you for your help.

+3
source share
1 answer
UPDATE t1
SET x = (
    SELECT SUM(t1.s LIKE CONCAT('%', t2.c, '%'))
    FROM t2
)

Explanation: the expression t1.s LIKE CONCAT('%', t2.c, '%')will be evaluated to a boolean value that is equivalent to 1either 0in MySQL.

I have not tested it, so please tell me if it works.

+4
source

Source: https://habr.com/ru/post/1773481/


All Articles