【问题标题】:Mysql select only numbers from substring resultMysql 仅从子字符串结果中选择数字
【发布时间】:2020-08-30 15:24:54
【问题描述】:

我有这个问题

SELECT SUBSTRING(post_content,INSTR(post_content, '[table'),16) as substring,
ID FROM `wp276_posts`
WHERE `post_content` LIKE '%[table%' 
AND `post_status` = 'publish' 
ORDER BY `ID` ASC 

返回这个结果:

如何只选择子字符串的数字部分?

例如需要的结果:

+-----------+------+
| substring | ID   |
+-----------+------+
| 22        | 5072 |
+-----------+------+
| 67        | 5757 |
+-----------+------+
| 54        | 8550 |
+-----------+------+

【问题讨论】:

  • 请展示 post_content 的例子
  • 您没有使用 substring_index 的事实表明您当前的查询可能不是最佳的..
  • post_content 是一个 WordPress 帖子,可能是一切。如果找到以[table开头的字符串,我需要取id=后面的数字

标签: mysql sql substring


【解决方案1】:

SUBSTRING_INDEX 可能在这里工作:

SELECT
    post_content,
    SUBSTRING_INDEX(SUBSTRING_INDEX(post_content, '[table id=', -1), ' ', 1) AS id
FROM wp276_posts
WHERE
    post_content LIKE '%[table%' AND
    post_status = 'publish'   -- you seem to want equivalence here
ORDER BY
    ID;

上面对SUBSTRING_INDEX 的内部调用会将所有内容返回到[table id=右侧。然后,外部调用将获取空间的左侧,该空间假定跟随id 数字。

【讨论】:

  • 对您的答案进行一点编辑似乎有效:SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(post_content, '[table id=', -1), ' ', 1) AS substring, ID FROM wp276_posts WHERE post_content LIKE '%[table%' AND post_status = 'publish' ORDER BY IDASC
【解决方案2】:

对于固定文本,您可以使用 REPLACE

SELECT 
    REPLACE(REPLACE(post_content," /]",""),"[tabelid= ","") as substring
    , ID 
FROM 
    `wp276_posts` 
WHERE 
    `post_content` LIKE '%[table%' 
    AND `post_status` LIKE 'publish' 
ORDER BY `ID` ASC 

【讨论】:

    【解决方案3】:

    是的,您可以使用SUBSTRING()INSTR() 功能组合:

    SELECT SUBSTRING(post_content,INSTR(post_content, 'id=')+3,
                     INSTR(post_content, ' /') - INSTR(post_content, 'id=') - 3
                     ) as substring, ID
      FROM t
     WHERE .....
    

    Demo

    【讨论】:

      猜你喜欢
      • 2012-06-06
      • 2014-11-25
      • 1970-01-01
      • 2014-04-19
      • 1970-01-01
      • 2014-08-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多