Mysq请求|从表格中的字符串中获取数字

时间:2018-05-25 18:06:44

标签: php mysql

我有一张带有记录的产品表(产品):

id name
1  1969-1972 Chevrolet Small Block 
2  1971-1975 Chevrolet Small Block Fan Shroud
3  1964 Chevrolet Bumper Kit Complete
4  Chevrolet Clutch And Brake Pedal Assembly
...

现在我想让请求结束提取前四个数字作为开始日期,并将字符串从6到9作为结束日期。

所以结果表将是:

id name                                             start end
 1  1969-1972 Chevrolet Small Block                 1969  1972
 2  1971-1975 Chevrolet Small Block Fan Shroud      1971  1975
 3  1964 Chevrolet Bumper Kit Complete              1964  null
 4  Chevrolet Clutch And Brake Pedal Assembly       null  null     
 ...

谢谢!

2 个答案:

答案 0 :(得分:1)

 1. LEFT(name , 4) as start; 
 2. CAST(SUBSTRING(name, 6, 4) AS UNSIGNED) as end;

答案 1 :(得分:1)

您可以通过一些REGEXP匹配使查询更加健壮,例如

SELECT id, 
  name,
  CASE WHEN name REGEXP '^[[:digit:]]{4}[ -]' THEN CAST(LEFT(name, 4) AS UNSIGNED)
  ELSE NULL
  END AS start,
  CASE WHEN name REGEXP '^[[:digit:]]{4}-[[:digit:]]{4} ' THEN CAST(SUBSTRING(name, 6, 4) AS UNSIGNED)
  ELSE NULL
  END AS end
FROM products

输出:

id  name                                        start   end
1   1969-1972 Chevrolet Small Block             1969    1972
2   1971-1975 Chevrolet Small Block Fan Shroud  1971    1975
3   1964 Chevrolet Bumper Kit Complete          1964    (null)
4   Chevrolet Clutch And Brake Pedal Assembly   (null)  (null)

如果您愿意,甚至可以从名称中删除重复的年份信息:

SELECT id, 
  CASE WHEN name REGEXP '^[[:digit:]]{4}-[[:digit:]]{4} ' THEN SUBSTRING(name, 10)
       WHEN name REGEXP '^[[:digit:]]{4} ' THEN SUBSTRING(name, 6)
       ELSE name 
  END AS name,
  CASE WHEN name REGEXP '^[[:digit:]]{4}[ -]' THEN CAST(LEFT(name, 4) AS UNSIGNED)
  ELSE NULL
  END AS start,
  CASE WHEN name REGEXP '^[[:digit:]]{4}-[[:digit:]]{4} ' THEN CAST(SUBSTRING(name, 6, 4) AS UNSIGNED)
  ELSE NULL
  END AS end
FROM products

输出:

id  name                                        start   end
1   Chevrolet Small Block                       1969    1972
2   Chevrolet Small Block Fan Shroud            1971    1975
3   Chevrolet Bumper Kit Complete               1964    (null)
4   Chevrolet Clutch And Brake Pedal Assembly   (null)  (null)