使用LOCATE和SUBSTRING从MySQL返回特定文本

时间:2013-07-28 18:19:49

标签: mysql regex substring locate

我想知道在我的NFL SQL数据库中运行了多少码。我使用以下查询:

Select season, description, down, ydsto1st
FROM nflpxp
WHERE 
(
   DESCRIPTION LIKE "%up the middle%" 
   OR DESCRIPTION REGEXP "(left|right) (tackle|guard|end)" 
   OR DESCRIPTION REGEXP " rushe(d|s) for "
)
AND season = 2012 AND off = 'WAS'
GROUP BY id

返回

season  description down    ydsto1st
2012    (13:58) (Shotgun) R.Griffin right end to WAS 44 for 12 yards (S.Shanle).    2   10
2012    (11:23) A.Morris right tackle to NO 27 for 3 yards (C.Jordan).  1   10
2012    (10:44) (Shotgun) A.Morris right guard to NO 25 for 2 yards (S.Shanle; B.Bunkley).  2   7
2012    (8:30) (Shotgun) A.Morris right guard to NO 22 for 2 yards (W.Smith).   2   15

我想在我的查询中添加一个列,从“为 nn 码”

提取码数

我试过了:

SELECT LEFT (description, LOCATE(' yards', description, 2)-1) AS yards FROM nflPxP

但它没有用。任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:0)

这样的事情应该有用;

SELECT 
      SUBSTRING_INDEX(
        LEFT(description, 
          GREATEST(LOCATE(' yards (', description),
                   LOCATE(' yard (',  description))-1), ' ', -1)
FROM nflPxP

An SQLfiddle to test with

虽然此查询适用于某些其他搜索条件提取的行,但它不可索引,因此如果需要搜索数据,您可能只想添加一个单独的列来存储数据。