我正在尝试用 a.name
在 b.content
中出现的次数填充 a.total
列。
a b
+--------------+ +----------------------+
| name | total | | content |
+------+-------+ +----------------------+
| foo | 3 | | hello bar |
| bar | 4 | | hola foofoo |
+--------------+ | nihao foo, bye bar |
| et bar se bar |
+----------------------+
我尝试了以下命令:
UPDATE a SET a.total = (SELECT COUNT(*) FROM b WHERE b.content LIKE CONCAT('%', a.name, '%') );
但我明白了:
Query OK, 0 rows affected (0.16 sec)
Rows matched: 4321 Changed: 0 Warnings: 0" with my command
这个命令有什么问题?我怎样才能考虑同一 content
行中所有出现的 foo
和 bar
?
最佳答案
Count the number of occurrences of a string in a VARCHAR field?显示如何计算列中子字符串的出现次数。然后,您可以将它们相加以获得所有行的总计。
UPDATE a
SET a.total = (
SELECT SUM((CHAR_LENGTH(b.content) - CHAR_LENGTH(REPLACE(b.content, a.name, ''))) / CHAR_LENGTH(a.name))
FROM b
WHERE b.content LIKE CONCAT('%', a.name, '%'))
关于MySQL:从表 'a.total' 的列 'a.name' 中的值 'b.content' 的计数中填充列 'b',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55507334/