RSS | Archive | Random | E-mail

About

Hi, I'm Christian Castelli, a 28 years old italian programmer located in Pisa (Italy). Here I post small snippets of code which can be useful in my work.

Links

Codepuzzling main site
Development site
ByteStrike italian blog
Follow me on Twitter

My Life Style

while(passion) {
  try {
    myLife.run();
  }catch(LifeExceptions) {  
    stronger++;
    continue;
   }
}

Following

8 September 09

[MySQL] How to clean URL with a function

Suppose that you have a table with a column named “referer” which stores referring urls and suppose that you want to update this column by cutting off everything but the domain and subdomain. Here it is a small function that does the job:

delimiter //
drop function if exists sub_domain;
CREATE FUNCTION sub_domain (url text(1000)) RETURNS CHAR(100)
BEGIN
DECLARE str1 varchar(10);
DECLARE str2 varchar(10);
SET str1="http://";
SET str2="https://";
RETURN if(substring_index(substring_index( substring_index(REPLACE(url,str2,str1), '/',3),str1,-1),'.',-1) != 'com', substring_index( substring_index( substring_index(REPLACE(url,str2,str1), '/',3),str1,-1),'.',-3), substring_index( substring_index( substring_index(REPLACE(url,str2,str1), '/',3),str1,-1),'.',-3));
END;
//
You can use it in this way:
UPDATE `mytable` 
SET `referer` = (SELECT sub_domain(`referer`));
From: MySQL substring syntax doc page

Tags: mysql SQL
Comments (View)
blog comments powered by Disqus
Themed by Hunson. Originally by Josh