在MySQL数据库5.5.62版上使用SUBSTRING_INDEX语法

时间:2020-07-09 09:33:48

标签: mysql string substring

MySQL数据库版本为5.5.62

这是我的桌子

mysql> SELECT * FROM `dotablenew`;
+-----+-------------+
| sID | sStringNew  |
+-----+-------------+
|   1 | D1080 ARE A |
|   2 | D5258 SEG   |
|   3 | D0749 COR   |
|   4 | D4278 VAI   |
|   5 | D2664 PON   |
+-----+-------------+
5 rows in set

我需要此退货

+-------+------+
| sOne  | sTwo |
+-------+------+
| D1080 | ARE  |
| D5258 | SEG  |
| D0749 | COR  |
| D4278 | VAI  |
| D2664 | PON  |
+-------+------+

我已经尝试过此解决方案

mysql> SELECT
    SUBSTRING_INDEX(sStringNew, ' ', 1) AS sOne,
    SUBSTRING_INDEX(sStringNew, ' ', - 1) AS sTwo
FROM
    `dotablenew`;
+-------+------+
| sOne  | sTwo |
+-------+------+
| D1080 | A    |
| D5258 | SEG  |
| D0749 | COR  |
| D4278 | VAI  |
| D2664 | PON  |
+-------+------+
5 rows in set

没有成功,因为第一行是错误的

+-------+------+
| sOne  | sTwo |
+-------+------+
| D1080 | A    |
+-------+------+

我真的不知道字符串 sStringNew 中可以有多少空格,但是我总是需要提取字符串 sStringNew 中用空格隔开的前两个元素。 ..

该如何解决?

请提出任何建议

我的下面的桌子

DROP TABLE IF EXISTS `dotablenew`;
CREATE TABLE `dotablenew` (
  `sID` int(11) NOT NULL AUTO_INCREMENT,
  `sStringNew` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`sID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of dotablenew
-- ----------------------------
INSERT INTO `dotablenew` VALUES ('1', 'D1080 ARE A');
INSERT INTO `dotablenew` VALUES ('2', 'D5258 SEG');
INSERT INTO `dotablenew` VALUES ('3', 'D0749 COR');
INSERT INTO `dotablenew` VALUES ('4', 'D4278 VAI');
INSERT INTO `dotablenew` VALUES ('5', 'D2664 PON');

2 个答案:

答案 0 :(得分:2)

SELECT sStringNew, 
    SUBSTRING_INDEX(sStringNew, ' ', 1) AS sOne,
    SUBSTRING_INDEX(SUBSTRING_INDEX(sStringNew, ' ',  2), ' ', -1) AS sTwo
FROM
    `dotablenew`

答案 1 :(得分:1)

尝试一下:

SELECT
    SUBSTRING_INDEX(sStringNew, ' ', 1) AS sOne,
    REVERSE(SUBSTRING_INDEX(REVERSE(SUBSTRING_INDEX(sStringNew, ' ', 2)), ' ', 1)) AS sTwo
FROM
    `dotablenew`