1

The version of MySQL database is 5.5.62

This is my table

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

I need this return

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

And I have tried this solution

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

Without success because the first row is wrong

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

I really don't know how many spaces can be in the string sStringNew but I always need to extract the first two elements of the string sStringNew separated by space...

How to do resolve this?

Please, any suggestion

My table below

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');
1
  • Haven't seen someone explaining the question this much nicely. Commented Jul 9, 2020 at 9:47

2 Answers 2

2
SELECT sStringNew, 
    SUBSTRING_INDEX(sStringNew, ' ', 1) AS sOne,
    SUBSTRING_INDEX(SUBSTRING_INDEX(sStringNew, ' ',  2), ' ', -1) AS sTwo
FROM
    `dotablenew`
Sign up to request clarification or add additional context in comments.

1 Comment

Better answer than mine.
1

Try this:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.