【问题标题】:Mysql: search for a substring and return the one with the highest # to the right of itMysql:搜索一个子字符串并返回它右侧的最高#
【发布时间】:2014-12-11 19:22:25
【问题描述】:

我需要在 mysql 字段中的字符串中搜索子字符串并返回它右侧的数字,如果它是返回的所有行中的最大数字。 (这个词很可能会在字符串中出现很多次。)

SELECT max(cast(substring(mq.my_query_string, (locate("near/", mq.my_query_string)+5), 2) as signed)) AS "MaxNearDistance" 
FROM my_query mq, my_test mt 
WHERE mt.company_id = 123 
      AND mq.search_query_id = mt.my_query_id 
      AND locate("near/", mq.my_query_string) > 0;

这行得通,但它只给了我最大数量的 FIRST 子字符串和所有返回的行。我需要子字符串和所有行的所有命中中的最高数字。

感谢您的帮助!

【问题讨论】:

  • 示例数据会有所帮助。除了'near'之外还有其他词吗?都是5位数的数字吗?
  • 数字为 1 到 2 位数字,显示如下:“near/12”。谢谢!

标签: mysql


【解决方案1】:

我将创建一个表格 - numbers- 包含我希望能够找到的每个数字字符串('0' - '99' 为你),然后将其加入我的数据,例如:

SELECT
  mq.my_query_string, MAX(numbers.ns)
FROM my_query AS mq
JOIN numbers ON CONCAT(mq.my_query_string, ' ') LIKE CONCAT('%near ', numbers.ns, ' %')
GROUP BY mq.my_query_string

我在CONCAT为数据添加一个空格,这样“11”就不会匹配“1”。

这里的 SQLFiddle:http://sqlfiddle.com/#!2/8fda1c/4

(实际上,正确的方法是规范化您的数据,这样您就有一个 my_query_nears 表,每行一个值,但有时我们必须玩我们的手。)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-26
    • 1970-01-01
    • 2014-04-02
    • 2021-09-27
    • 2015-12-18
    相关资源
    最近更新 更多