【问题标题】:Search for strings with multiple {tokens} in database在数据库中搜索具有多个 {tokens} 的字符串
【发布时间】:2012-04-18 18:56:19
【问题描述】:

考虑下表中的消息。其中一些有一个或多个{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 中)计算消息中标签的数量并只返回其中包含一个或两个标签的消息?

【问题讨论】:

  • 您可以使用嵌套的 indexof 调用并断言第三个 indested 调用返回 -1

标签: mysql sql


【解决方案1】:
SELECT * FROM messages WHERE (LENGTH(message) - LENGTH(REPLACE(message,'{bar|','')))/5 BETWEEN 1 AND 2;

这应该可行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-19
    • 2022-01-03
    相关资源
    最近更新 更多