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

24 May 10

A view fro MySQL triggers

Here it is a small view to see all triggers stored in the DBMS. IMHO it’s more usable than going into INFORMATION_SCHEMA database and browse TRIGGERS records.

CREATE VIEW `List_triggers` AS
SELECT `TRIGGER_NAME` AS `Name`, `TRIGGER_SCHEMA` AS `Database`,
	   `EVENT_OBJECT_TABLE` AS `Table`,
	   CONCAT_WS(" ", ACTION_TIMING, EVENT_MANIPULATION) AS `Action`
FROM `INFORMATION_SCHEMA`.`TRIGGERS`

Comments (View)
9 September 09

[MySQL] How to create a random day for a date

If you have extracted with PHP or a SQL function a date (“YYYY-MM-DD”) and you want to change the day with a random day, here is it a series of SELECT for doing it:

SELECT date FROM (
-- generates a number x between 1 and 27
	SELECT @rand:=(
		SELECT FLOOR(1 + (RAND() * 27))
	) as rand, 
		    DATE_ADD('2006-05-01',INTERVAL @rand DAY) as date
) as t; -- give an alias, otherwise it's uncorrect

Comments (View)
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)
4 September 09

[MySQL] How to swap columns values in a table

I find a very useful webpage on how to swap columns values in MySQL. In that article are presented three methods, of which I’ve chosen the following one which makes use of a temporary variable:

UPDATE table
SET x=(@temp:=x), x = y, y = @temp 
WHERE condition....

Tags: MySQL SQL
Comments (View)
1 September 09

[SQL] How to concatenate a string with a result of a query

If the subquery returns a string, you can use safely CONCAT operator to join the strings:
SELECT CONCAT('my',(SELECT string
                   FROM table
                   WHERE condition = 1)) as aName
You can use CONCAT_WS if you want to specify a separator for the strings.

Tags: SQL mysql
Comments (View)
21 June 09

How to export to an array a MySQL query with 3 lines of code

By reading a good contribution on PHP site, I discovered this method for exporting to an array a query submitted to MySQL:
$result = mysql_query("SELECT * FROM table");
for($i = 0; $array[$i] = mysql_fetch_assoc($result); $i++) ;
array_pop($array); // removes last empty array
It produces:
Array
(
    [0] => Array
        (
            [id] => 1
            [user] => myuser
            [pass] => mypass
            ... other fields
        )
    ... and so on
That’s to say you’ll have count($array) records, of which every row has count($array[0]) fields.

Tags: mysql php SQL
Comments (View)
8 June 09

[SQL] How to compare two SQL schema with sqlfairy

First of all, install sqlfairy on your machine if you haven’t done yet, then simply give in input to the program the path to the SQL schemas:

sqlt-diff -d -c schema_to_update.sql=MySQL updated_schema.sql=MySQL 2>/dev/null|grep -v "DROP TABLE"

Notes on this command:
  • -d: prints debug info;
  • -c: case insensitive;
  • 2>/dev/null: don’t print warning and error messages so you can grep results data;
  • grep -v “word”: don’t print lines that match the pattern specified between quotes
Tags: sql bash
Comments (View)
4 March 09

Which quotes have more than X services?

SELECT id, COUNT(productid) as numProd 
FROM `vtiger_inventoryproductrel`
WHERE id IN (SELECT quoteid FROM vtiger_quotes, vtiger_crmentity
                      WHERE quoteid = crmid AND deleted = 0)
GROUP BY id 
HAVING numProd > 4 

Tags: vtiger sql crm
Comments (View)
Themed by Hunson. Originally by Josh