Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysql substring_index reverse

Tags:

string

mysql

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?

like image 914
user121196 Avatar asked May 19 '12 05:05

user121196


2 Answers

    select substr('www.java2s.sth.com', 1, (length('www.java2s.sth.com')- 
    length(SUBSTRING_INDEX(('www.java2s.sth.com'), '.', -1))-1));`
like image 185
Afshin Moazami Avatar answered Oct 17 '22 00:10

Afshin Moazami


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)));
like image 30
dgpro Avatar answered Oct 17 '22 01:10

dgpro