Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SUBSTRING_INDEX with multiple delimiters

Tags:

mysql

I am trying to remove some information off urls that are placed into my database. I have this query that I am using:

Select substring_index(refurl,'?gclid',1) as refurl, Count(*)
from leads
group by substring_index(refurl,'?gclid',1)

But for the delimiter I really need to take off both of these:

?gclid or &gclid 

Is this possible by doing an OR statement within the substring or is it something completely different to get this done?

like image 728
NickC217 Avatar asked Mar 20 '14 01:03

NickC217


2 Answers

Use IF

SELECT SUBSTRING_INDEX(refurl, IF(LOCATE('?gclid', refurl), '?gclid', '&gclid'), 1) AS refurl, ...
like image 182
Barmar Avatar answered Oct 23 '22 13:10

Barmar


Just in case, I just needed to group strings before a certain number, ex:

hcu
----------------------
AQP Casma 01 HCU 200
AQP Casma 10 HCU 1500
AQP Casma 11 HCU 1500
Cusco 1 HCU 1500
Cusco 2 HCU 200-3
Cusco 3 HCU 200-1
Cusco 12 HCU 200

to obtain only this:

AQP Casma
Cusco

I couldn't use IF because the multiple delimiters, so the query that I've used is:

SELECT 
 CASE 
    WHEN LOCATE(' 0',hcu )>0 THEN SUBSTRING_INDEX(hcu, '0', 1)
    WHEN LOCATE(' 1',hcu )>0 THEN SUBSTRING_INDEX(hcu, '1', 1)  
END hub  
FROM npi_hist 
GROUP BY hub 

And the result was the expected... I don't know why is grouping correctly all the Cusco registers, but It's working as I needed.

Hope it could help.

Bye.

like image 29
200313 Avatar answered Oct 23 '22 13:10

200313