6

in MYSQL, given a string with dots in it, I want to select everything before the last dot. for example: input

www.java2s.com

output:

www.java2s

substring_index seems to do the opposite:

mysql> SELECT SUBSTRING_INDEX('www.java2s.com', '.', -1);
+--------------------------------------------+
| SUBSTRING_INDEX('www.java2s.com', '.', -1) |
+--------------------------------------------+
| com                                        |
+--------------------------------------------+

can this be done?

3 Answers 3

6
    select substr('www.java2s.sth.com', 1, (length('www.java2s.sth.com')- 
    length(SUBSTRING_INDEX(('www.java2s.sth.com'), '.', -1))-1));`
Sign up to request clarification or add additional context in comments.

Comments

6

If you are looking for a nicer solution here it is:

SET @domain = "www.java2s.com";
SELECT SUBSTRING(@domain, 1, LENGTH(@domain)-LOCATE('.', REVERSE(@domain)));

Comments

1

use this

SELECT SUBSTRING_INDEX('www.java2s.com', '.', 2)

more generic

SELECT SUBSTRING_INDEX('www.java2s.com', '.', ( LENGTH('www.java2s.com') - LENGTH(REPLACE('www.java2s.com', '.', '')))  )

1 Comment

the problem is that I don't know how many dots are in the file, I don't know it's 2 or x

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.