MySQL:循环遍历一个表并更新另一个表?

发布于 2024-10-01 04:16:51 字数 581 浏览 2 评论 0原文

表 t1:

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

表 t2:

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

我想为 t1.s 中出现的每个字符 t2.c 添加 +1 到 t1.x,即结果应该是这样的:

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

Looping through t2 and update t1 in php is相当简单,但如果可能的话,我宁愿用纯 SQL 来完成。

感谢您的帮助。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

蛮可爱 2024-10-08 04:16:51
UPDATE t1
SET x = (
    SELECT SUM(t1.s LIKE CONCAT('%', t2.c, '%'))
    FROM t2
)

说明:表达式 t1.s LIKE CONCAT('%', t2.c, '%') 将计算为布尔值,相当于 1MySQL 中的 0

我没有测试它,所以如果它不起作用,请告诉我。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文