考虑下表中的消息。其中一些有一个或多个 {bar|***}
形式的标签,其中 ***
可以是任何东西(字母、数字、标点符号)。
id message
---------------------------------------------------
1 foo {bar|112} baz {bar|foo} {bar|215.54}
2 lorem ipsum {bar|foo} dolor {bar|samet} digitas
3 last {bar|t} label example
4 string with no label
5 another {zoo} string with {foo|ads} label
如果我想查找所有带有至少一个 {bar|*} 形式标签的邮件,我查询:
SELECT * FROM messages WHERE message LIKE '%{bar|%';
但是现在,我需要一个查询,通过它我只能选择那些至多两个这样的标签的消息:
id message
---------------------------------------------------
2 lorem ipsum {bar|foo} dolor {bar|samet} digitas
3 last {bar|t} label example
换句话说:有没有一种方法(在 MySQL 中)可以计算消息中标签的数量,并只返回其中包含一个或两个标签的消息?
最佳答案
SELECT * FROM messages WHERE (LENGTH(message) - LENGTH(REPLACE(message,'{bar|','')))/5 BETWEEN 1 AND 2;
这应该有效。
关于mysql - 在数据库中搜索具有多个 {tokens} 的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10216057/