<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>SIMOTRONE WEB PAGE &#187; Mysql</title>
	<atom:link href="http://www.simotrone.it/tag/mysql/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.simotrone.it</link>
	<description>Simotrone is always here!</description>
	<lastBuildDate>Sat, 04 Feb 2012 18:30:44 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.1</generator>
		<item>
		<title>Drop UNIQUE</title>
		<link>http://www.simotrone.it/2011/10/24/drop-unique/</link>
		<comments>http://www.simotrone.it/2011/10/24/drop-unique/#comments</comments>
		<pubDate>Mon, 24 Oct 2011 05:16:24 +0000</pubDate>
		<dc:creator>Simotrone</dc:creator>
				<category><![CDATA[Binary People]]></category>
		<category><![CDATA[Mysql]]></category>

		<guid isPermaLink="false">http://www.simotrone.it/?p=3582</guid>
		<description><![CDATA[In MySQL UNIQUE equivale ad un indice sulla colonna. Nel caso si voglia cancellare la proprietà UNIQUE si può usare DROP INDEX. DROP INDEX nome_indice ON tabella Il &#8220;nome_indice&#8221; coincide spesso con il nome della colonna (a parte la chiave primaria che si chiama &#8220;PRIMARY&#8221;). Comunque, in caso di dubbi: SHOW INDEX FROM tabella]]></description>
			<content:encoded><![CDATA[<p>In MySQL UNIQUE equivale ad un indice sulla colonna.<br />
Nel caso si voglia cancellare la proprietà UNIQUE si può usare <a href="http://dev.mysql.com/doc/refman/5.0/en/drop-index.html">DROP INDEX</a>.</p>
<pre>DROP INDEX nome_indice ON tabella</pre>
<p>Il &#8220;nome_indice&#8221; coincide  spesso con il nome della colonna (a parte la chiave primaria che si chiama &#8220;PRIMARY&#8221;). Comunque, in caso di dubbi:</p>
<pre>SHOW INDEX FROM tabella</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.simotrone.it/2011/10/24/drop-unique/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>SQL no LIMIT</title>
		<link>http://www.simotrone.it/2011/05/01/sql-no-limit/</link>
		<comments>http://www.simotrone.it/2011/05/01/sql-no-limit/#comments</comments>
		<pubDate>Sun, 01 May 2011 05:27:44 +0000</pubDate>
		<dc:creator>Simotrone</dc:creator>
				<category><![CDATA[Binary People]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[limit]]></category>
		<category><![CDATA[Mysql]]></category>

		<guid isPermaLink="false">http://www.simotrone.it/?p=3338</guid>
		<description><![CDATA[Mi sono sempre chiesto se LIMIT tagliasse i dati &#8220;a monte&#8221; della query o &#8220;a valle&#8221;&#8230; Un tempo mettevo LIMIT convinto che servisse, poi mi sono accorto &#8220;a naso&#8221; che non pareva proprio così&#8230; Una discussione in giro per irc ha chiarito il punto. Temevo che fosse come in effetti e&#8217;: LIMIT taglia i risultati [...]]]></description>
			<content:encoded><![CDATA[<p>Mi sono sempre chiesto se LIMIT tagliasse i dati &#8220;a monte&#8221; della query o &#8220;a valle&#8221;&#8230;<br />
Un tempo mettevo LIMIT convinto che servisse, poi mi sono accorto &#8220;a naso&#8221; che non pareva proprio così&#8230;<br />
Una discussione in giro per irc ha chiarito il punto.</p>
<p>Temevo che fosse come in effetti e&#8217;: LIMIT taglia i risultati dopo che la query è stata eseguita e i record trovati sono molto più di quelli che vengono restituiti. (cit. <a href="http://datacharmer.blogspot.com/">datacharmer</a>).</p>
<pre>web:Agenda> SELECT SQL_CALC_FOUND_ROWS * FROM folks LIMIT 1;
+----+------+----------+------------+--------+---------------------+---------------------+--------+
| id | name | surname  | birth      | gender | created             | updated             | active |
+----+------+----------+------------+--------+---------------------+---------------------+--------+
|  1 | xxxx | xxxxxxxx | 1973-06-02 | m      | 2010-02-11 20:11:00 | 2010-02-13 17:33:04 |      1 |
+----+------+----------+------------+--------+---------------------+---------------------+--------+
1 row in set (0.00 sec)

web:Agenda> SELECT FOUND_ROWS();
+--------------+
| FOUND_ROWS() |
+--------------+
|          101 |
+--------------+
1 row in set (0.00 sec)

web:Agenda> SELECT SQL_CALC_FOUND_ROWS * FROM folks WHERE id=1;
+----+------+----------+------------+--------+---------------------+---------------------+--------+
| id | name | surname  | birth      | gender | created             | updated             | active |
+----+------+----------+------------+--------+---------------------+---------------------+--------+
|  1 | xxxx | xxxxxxxx | 1973-06-02 | m      | 2010-02-11 20:11:00 | 2010-02-13 17:33:04 |      1 |
+----+------+----------+------------+--------+---------------------+---------------------+--------+
1 row in set (0.01 sec)

web:Agenda> SELECT FOUND_ROWS();
+--------------+
| FOUND_ROWS() |
+--------------+
|            1 |
+--------------+
1 row in set (0.00 sec)</pre>
<p>Un WHERE ben piazzato (se si può mettere), è ben più efficace. Ooookei.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.simotrone.it/2011/05/01/sql-no-limit/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Meta-dati in MySQL (2)</title>
		<link>http://www.simotrone.it/2010/09/30/meta-dati-in-mysql-2/</link>
		<comments>http://www.simotrone.it/2010/09/30/meta-dati-in-mysql-2/#comments</comments>
		<pubDate>Thu, 30 Sep 2010 05:49:31 +0000</pubDate>
		<dc:creator>Simotrone</dc:creator>
				<category><![CDATA[Binary People]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[information_scheme]]></category>
		<category><![CDATA[Mysql]]></category>

		<guid isPermaLink="false">http://www.simotrone.it/?p=3069</guid>
		<description><![CDATA[Avendo un database in mano mai visto ma progettato decentemente, può essere interessante cercare di valutare se ci sono campi utili per linkare le relazioni fra di loro (e valutare prima di una modifica quali relazioni dovrebbero essere toccate). (Spesso i campi per creare questi collegamenti sono dei field *_id che si ripetono nelle relazioni [...]]]></description>
			<content:encoded><![CDATA[<p>Avendo un database in mano mai visto ma progettato decentemente, può essere interessante cercare di valutare se ci sono campi utili per linkare le relazioni fra di loro (e valutare prima di una modifica quali relazioni dovrebbero essere toccate). (Spesso i campi per creare questi collegamenti sono dei field <strong>*_id</strong> che si ripetono nelle relazioni interessate.)</p>
<p>Ho avuto la necessità quindi di vedere quante e quali relazioni facessero uso di un determinato campo in un database (o, detta in soldoni, ho cercato di capire dove fossero presenti determinate colonne nelle tabelle del database).</p>
<div class="codesnip-container" >
<div class="codesnip" style="font-family: monospace;"><span class="kw1">SELECT</span> table_name, column_name <span class="kw1">FROM</span> information_schema.<span class="kw1">COLUMNS</span> <span class="kw1">WHERE</span> table_schema = <span class="st0">&#8216;database&#8217;</span> <span class="kw1">AND</span> column_name <span class="kw1">LIKE</span> <span class="st0">&#8216;%_id&#8217;</span>;</div>
</div>
<p>Win. Almeno so dove guardare. <img src='http://www.simotrone.it/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.simotrone.it/2010/09/30/meta-dati-in-mysql-2/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Meta-dati in MySQL</title>
		<link>http://www.simotrone.it/2010/09/22/meta-dati-in-mysql/</link>
		<comments>http://www.simotrone.it/2010/09/22/meta-dati-in-mysql/#comments</comments>
		<pubDate>Wed, 22 Sep 2010 05:48:19 +0000</pubDate>
		<dc:creator>Simotrone</dc:creator>
				<category><![CDATA[Binary People]]></category>
		<category><![CDATA[information_scheme]]></category>
		<category><![CDATA[Mysql]]></category>
		<category><![CDATA[SQL]]></category>

		<guid isPermaLink="false">http://www.simotrone.it/?p=3065</guid>
		<description><![CDATA[Smanettando nei database può capitare di essere incuriositi da alcune relazioni dentro un database (quando si passa attraverso framework già preparati da qualcun&#8217;altro, può fare comodo capire cose a grandi linee). In MySQL, i metadati dei database e delle tabelle sono nella tabella &#8220;di sistema&#8221; information_scheme. Quante righe hanno le tabelle di quel database? Se [...]]]></description>
			<content:encoded><![CDATA[<p>Smanettando nei database può capitare di essere incuriositi da alcune relazioni dentro un database (quando si passa attraverso <em>framework</em> già preparati da qualcun&#8217;altro, può fare comodo capire cose <em>a grandi linee</em>).<br />
In MySQL, i metadati dei database e delle tabelle sono nella tabella &#8220;di sistema&#8221; <a href="http://dev.mysql.com/doc/refman/5.1/en/information-schema.html">information_scheme</a>.</p>
<p><em>Quante righe hanno le tabelle di quel database?</em><br />
Se non vogliamo usare <strong>mysqlshow</strong> <a href="http://www.simotrone.it/2010/02/10/mysqlshow/">come spiegato in precedenza</a> possiamo operare da dentro il server:</p>
<div class="codesnip-container" >
<div class="codesnip" style="font-family: monospace;"><span class="kw1">SELECT</span> table_name, table_rows <span class="kw1">FROM</span> information_schema.<span class="kw1">TABLES</span> <span class="kw1">WHERE</span> table_schema = <span class="st0">&#8216;Agenda&#8217;</span> <span class="kw1">ORDER</span> <span class="kw1">BY</span> table_rows <span class="kw1">DESC</span>;</div>
</div>
<p>Risultato:</p>
<pre>+------------+------------+
| table_name | table_rows |
+------------+------------+
| folks      |         95 |
| info       |         47 |
| addresses  |         31 |
| phones     |         11 |
| emails     |          2 |
+------------+------------+
5 rows in set (0.04 sec)</pre>
<p>Nel mio caso specifico la query è stata utile per sapere quante tabelle in un framework potevo evitare di guardare (quelle con 0 righe). <img src='http://www.simotrone.it/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<p>Se nel delirio più totale si vogliono sapere quali utenti ci sono del db-server (ché non ce li si ricorda più dopo un po&#8217;)</p>
<div class="codesnip-container" >
<div class="codesnip" style="font-family: monospace;"><span class="kw1">SELECT</span> host,user <span class="kw1">FROM</span> mysql.user</div>
</div>
<p>e quali db hanno in mano&#8230; <img src='http://www.simotrone.it/wp-includes/images/smilies/icon_razz.gif' alt=':-P' class='wp-smiley' /> </p>
<div class="codesnip-container" >
<div class="codesnip" style="font-family: monospace;"><span class="kw1">SELECT</span> user, db <span class="kw1">FROM</span> mysql.db</div>
</div>
<p>Altre cose interessanti si possono sicuramente trovare <a href="http://www.artfulsoftware.com/infotree/queries.php?&#038;bw=991">qua</a> (<a href="http://www.artfulsoftware.com/infotree/queries.php?&#038;bw=991">Common MySQL query</a>).</p>
<p>Come dicevo, la cosa può essere fatta anche con mysqlshow &#8211;count &#8211; che è talmente utile, da essere un alias a mysqlshow nel mio bashrc. <img src='http://www.simotrone.it/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.simotrone.it/2010/09/22/meta-dati-in-mysql/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Insiemistica e MySQL</title>
		<link>http://www.simotrone.it/2010/09/20/insiemistica-e-mysql/</link>
		<comments>http://www.simotrone.it/2010/09/20/insiemistica-e-mysql/#comments</comments>
		<pubDate>Mon, 20 Sep 2010 05:11:20 +0000</pubDate>
		<dc:creator>Simotrone</dc:creator>
				<category><![CDATA[Binary People]]></category>
		<category><![CDATA[intersezione]]></category>
		<category><![CDATA[meno]]></category>
		<category><![CDATA[minus]]></category>
		<category><![CDATA[Mysql]]></category>
		<category><![CDATA[SQL]]></category>

		<guid isPermaLink="false">http://www.simotrone.it/?p=3063</guid>
		<description><![CDATA[Un po&#8217; di insiemistica con tabelle SQL. Come faccio a sapere quali elementi sono in comune fra due relazioni? Intersezione SELECT a.member_id, a.name FROM a INNER JOIN b USING &#40;member_id, name&#41; Come faccio a sapere quali elementi non sono in comune fra due relazioni? Minus Con subquery: SELECT DISTINCT member_id, name FROM a WHERE &#40;member_id, [...]]]></description>
			<content:encoded><![CDATA[<p>Un po&#8217; di insiemistica con tabelle SQL.</p>
<p>Come faccio a sapere quali elementi sono in comune fra due relazioni?<br />
<strong>Intersezione</strong></p>
<div class="codesnip-container" >
<div class="codesnip" style="font-family: monospace;"><span class="kw1">SELECT</span> a.member_id, a.name <span class="kw1">FROM</span> a <span class="kw1">INNER</span> <span class="kw1">JOIN</span> b <span class="kw1">USING</span> <span class="br0">&#40;</span>member_id, name<span class="br0">&#41;</span></div>
</div>
<p>Come faccio a sapere quali elementi non sono in comune fra due relazioni?<br />
<strong>Minus</strong><br />
Con subquery:</p>
<div class="codesnip-container" >
<div class="codesnip" style="font-family: monospace;"><span class="kw1">SELECT</span> <span class="kw1">DISTINCT</span> member_id, name <span class="kw1">FROM</span> a <span class="kw1">WHERE</span> <span class="br0">&#40;</span>member_id, name<span class="br0">&#41;</span> <span class="kw1">NOT</span> <span class="kw1">IN</span> <span class="br0">&#40;</span><span class="kw1">SELECT</span> member_id, name <span class="kw1">FROM</span> table2<span class="br0">&#41;</span>;</div>
</div>
<p>Con join:</p>
<div class="codesnip-container" >
<div class="codesnip" style="font-family: monospace;"><span class="kw1">SELECT</span> <span class="kw1">DISTINCT</span> a.member_id, a.name <span class="kw1">FROM</span> a <span class="kw1">LEFT</span> <span class="kw1">JOIN</span> b <span class="kw1">USING</span> <span class="br0">&#40;</span>member_id, name<span class="br0">&#41;</span> <span class="kw1">WHERE</span> b.member_id <span class="kw1">IS</span> <span class="kw1">NULL</span></div>
</div>
<p><a href="http://www.bitbybit.dk/carsten/blog/?p=71">Riferimento</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.simotrone.it/2010/09/20/insiemistica-e-mysql/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>MySQL e timestamp, la vendetta</title>
		<link>http://www.simotrone.it/2010/03/02/mysql-e-timestamp-la-vendetta/</link>
		<comments>http://www.simotrone.it/2010/03/02/mysql-e-timestamp-la-vendetta/#comments</comments>
		<pubDate>Tue, 02 Mar 2010 06:25:24 +0000</pubDate>
		<dc:creator>Simotrone</dc:creator>
				<category><![CDATA[Binary People]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[Mysql]]></category>
		<category><![CDATA[timestamp]]></category>

		<guid isPermaLink="false">http://www.simotrone.it/?p=2691</guid>
		<description><![CDATA[Dopo gli accidenti tirati precedentemente, ho scoperto che dare un comando CHANGE su una colonna dichiarandola come TIMESTAMP ha il seguente effetto: il default diventa CURRENT_TIMESTAMP e l&#8217;extra è ON UPDATE CURRENT_TIMESTAMP. Avevo letto che CHANGE e MODIFY cancellavano gli attributi (l&#8217;Extra) delle colonne cui cambiavano il tipo, e così mi sono messo ad assegnare [...]]]></description>
			<content:encoded><![CDATA[<p>Dopo gli accidenti tirati precedentemente, ho scoperto che dare un comando CHANGE su una colonna dichiarandola come TIMESTAMP ha il seguente effetto: il default diventa CURRENT_TIMESTAMP e l&#8217;extra è ON UPDATE CURRENT_TIMESTAMP.</p>
<p>Avevo letto che CHANGE e MODIFY cancellavano gli attributi (<em>l&#8217;Extra</em>) delle colonne cui cambiavano il tipo, e così mi sono messo ad assegnare TIMESTAMP e DATETIME ai due campi created/updated in modo da togliermi i dubbi.<br />
(dal man: &#8220;<em>When you use CHANGE or MODIFY, column_definition must include the data type and all attributes that should apply to the new column, other than index attributes such as PRIMARY KEY or UNIQUE. Attributes present in the original definition but not specified for the new definition are not carried forward.</em>&#8220;)</p>
<pre>sim:test> ALTER TABLE A CHANGE created created DATETIME;
sim:test> ALTER TABLE A CHANGE updated updated TIMESTAMP;
[...]
| created | datetime    | YES  | | NULL              |                             |
| updated | timestamp   | NO   | | CURRENT_TIMESTAMP | on update CURRENT_TIMESTAMP |</pre>
<p>Alla fine mi sono un po&#8217; capito leggendo <a href="http://dev.mysql.com/doc/refman/5.1/en/timestamp.html">qua</a>.<br />
I dati di tipo <strong>timestamp</strong> dovrebbero essere dei <strong>datetime</strong> (e lo sono come formato), ma a differenza di questi ultimi si aggiornano con l&#8217;ora attuale.</p>
<p><em>The TIMESTAMP data type offers automatic initialization and updating.</em></p>
<p>Dopo aver reso la colonna updated CURRENT_TIMESTAMP con aggiornamento sull&#8217;UPDATE dei dati, ho potuto fare:</p>
<pre>ALTER TABLE A MODIFY created TIMESTAMP NOT NULL DEFAULT '0000-00-00 00:00:00';</pre>
<p>e inserire un paio di dati:</p>
<pre>sim:test> INSERT INTO A (word) VALUES ('gastone');
sim:test> INSERT INTO A (word,created) VALUES ('paperino',NULL);</pre>
<p>col risultato:</p>
<pre>|  5 | gastone  | 0000-00-00 00:00:00 | 2010-02-11 23:42:03 |
|  6 | paperino | 2010-02-11 23:42:23 | 2010-02-11 23:42:23 |</pre>
<p>Sul man c&#8217;è scritto pure questo, ma a me continua a sembrare un comportamento strano.<br />
<em>TIMESTAMP columns are NOT NULL by default, cannot contain NULL values, and assigning NULL assigns the current timestamp.</em></p>
<p>In conclusione, se volete avere dei campi con la creazione e l&#8217;aggiornamento automatico delle date incluso, leggetevi la <a href="http://dev.mysql.com/doc/refman/5.1/en/timestamp.html">pagina di Mysql sui timestamp</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.simotrone.it/2010/03/02/mysql-e-timestamp-la-vendetta/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>MySQL e timestamp vanno sulla luna</title>
		<link>http://www.simotrone.it/2010/02/23/mysql-e-timestamp-vanno-sulla-luna/</link>
		<comments>http://www.simotrone.it/2010/02/23/mysql-e-timestamp-vanno-sulla-luna/#comments</comments>
		<pubDate>Tue, 23 Feb 2010 06:10:55 +0000</pubDate>
		<dc:creator>Simotrone</dc:creator>
				<category><![CDATA[Binary People]]></category>
		<category><![CDATA[Mysql]]></category>
		<category><![CDATA[timestamp]]></category>

		<guid isPermaLink="false">http://www.simotrone.it/?p=2677</guid>
		<description><![CDATA[Qua c&#8217;è da uscire di senno. A me MySQL sta pure simpatico, ma fa veramente di tutto per farmi sentire male. Parto proprio dall&#8217;inizio. sim:none> CREATE DATABASE test CHARACTER SET = 'UTF8'; Query OK, 1 row affected (0.00 sec) sim:none> CONNECT test; Connection id: 230 Current database: test Ammettiamo che io voglia creare una tabella [...]]]></description>
			<content:encoded><![CDATA[<p>Qua c&#8217;è da uscire di senno. A me MySQL sta pure simpatico, ma fa veramente di tutto per farmi sentire male.</p>
<p>Parto proprio dall&#8217;inizio.</p>
<pre>sim:none> CREATE DATABASE test CHARACTER SET = 'UTF8';
Query OK, 1 row affected (0.00 sec)

sim:none> CONNECT test;
Connection id:    230
Current database: test</pre>
<p>Ammettiamo che io voglia creare una tabella canonica con vari campi, fra cui l&#8217;<strong>id</strong> come PK, un campo per segnare quando il record è stato creato (<strong>created</strong>) ed uno per segnarmi quando è stato aggiornato l&#8217;ultima volta (<strong>updated</strong>).</p>
<pre>sim:test> CREATE TABLE A (
    id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
    word VARCHAR(8) NOT NULL,
    created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated TIMESTAMP NOT NULL );
Query OK, 0 rows affected (0.00 sec)</pre>
<p>La situazione della mia tabella A per ora è chiara.</p>
<pre>sim:test> SHOW CREATE TABLE A \G;
*************************** 1. row ***************************
       Table: A
Create Table: CREATE TABLE `A` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `word` varchar(8) NOT NULL,
  `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8
1 row in set (0.00 sec)
</pre>
<p>Inserisco anche un paio di record che appaiono come ci si aspetta:</p>
<pre>sim:test> INSERT INTO A (word) VALUES ('pippo'),('pluto');
Query OK, 2 rows affected (0.00 sec)
Records: 2  Duplicates: 0  Warnings: 0

sim:test> SELECT * FROM A;
+----+-------+---------------------+---------------------+
| id | word  | created             | updated             |
+----+-------+---------------------+---------------------+
|  1 | pippo | 2010-02-11 22:23:41 | 0000-00-00 00:00:00 |
|  2 | pluto | 2010-02-11 22:23:41 | 0000-00-00 00:00:00 |
+----+-------+---------------------+---------------------+
2 rows in set (0.00 sec)
</pre>
<p>Nel caso si decida di aggiornare un record:</p>
<pre>sim:test> UPDATE A SET word = 'topolino' WHERE id=2;
Query OK, 1 row affected (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 0

sim:test> SELECT * FROM A;
+----+----------+---------------------+---------------------+
| id | word     | created             | updated             |
+----+----------+---------------------+---------------------+
|  1 | pippo    | 2010-02-11 22:23:41 | 0000-00-00 00:00:00 |
|  2 | topolino | 2010-02-11 22:23:41 | 0000-00-00 00:00:00 |
+----+----------+---------------------+---------------------+
2 rows in set (0.00 sec)</pre>
<p>A questo punto decido che questa disposizione dei dati non mi va più bene, che fare? <em>Semplice</em> (* le ultime parole famose <sup>TM</sup> ), leggo <a href="http://dev.mysql.com/doc/refman/5.1/en/alter-table.html">il manuale</a> e sistemo. Seee&#8230;</p>
<p>Un po&#8217; di pazzia MySQL:</p>
<pre>sim:test> SHOW COLUMNS FROM A;
+---------+------------------+------+-----+---------------------+----------------+
| Field   | Type             | Null | Key | Default             | Extra          |
+---------+------------------+------+-----+---------------------+----------------+
| id      | int(10) unsigned | NO   | PRI | NULL                | auto_increment |
| word    | varchar(8)       | NO   |     | NULL                |                |
| created | timestamp        | NO   |     | CURRENT_TIMESTAMP   |                |
| updated | timestamp        | NO   |     | 0000-00-00 00:00:00 |                |
+---------+------------------+------+-----+---------------------+----------------+
4 rows in set (0.00 sec)

sim:test> ALTER TABLE A ALTER created DROP DEFAULT;
Query OK, 0 rows affected (0.00 sec)
Records: 0  Duplicates: 0  Warnings: 0

sim:test> SHOW COLUMNS FROM A;
+---------+------------------+------+-----+---------------------+----------------+
| Field   | Type             | Null | Key | Default             | Extra          |
+---------+------------------+------+-----+---------------------+----------------+
| id      | int(10) unsigned | NO   | PRI | NULL                | auto_increment |
| word    | varchar(8)       | NO   |     | NULL                |                |
| created | timestamp        | NO   |     | NULL                |                |
| updated | timestamp        | NO   |     | 0000-00-00 00:00:00 |                |
+---------+------------------+------+-----+---------------------+----------------+
4 rows in set (0.00 sec)

sim:test> ALTER TABLE A CHANGE created creat TIMESTAMP;
Query OK, 0 rows affected (0.01 sec)
Records: 0  Duplicates: 0  Warnings: 0

sim:test> SHOW COLUMNS FROM A;
+---------+------------------+------+-----+---------------------+-----------------------------+
| Field   | Type             | Null | Key | Default             | Extra                       |
+---------+------------------+------+-----+---------------------+-----------------------------+
| id      | int(10) unsigned | NO   | PRI | NULL                | auto_increment              |
| word    | varchar(8)       | NO   |     | NULL                |                             |
| creat   | timestamp        | NO   |     | CURRENT_TIMESTAMP   | on update CURRENT_TIMESTAMP |
| updated | timestamp        | NO   |     | 0000-00-00 00:00:00 |                             |
+---------+------------------+------+-----+---------------------+-----------------------------+
4 rows in set (0.00 sec)</pre>
<p>Con un magico DROP del DEFAULT di un campo ed un cambio nome ottengo di nuovo il CURRENT_TIMESTAMP come default, e pure l&#8217;update automatico sul campo.</p>
<p>Provare per credere:</p>
<pre>sim:test> INSERT INTO A (word) VALUES ('minnie');
Query OK, 1 row affected (0.00 sec)

sim:test> SELECT * FROM A;
+----+----------+---------------------+---------------------+
| id | word     | creat               | updated             |
+----+----------+---------------------+---------------------+
|  1 | pippo    | 2010-02-11 22:23:41 | 0000-00-00 00:00:00 |
|  2 | topolino | 2010-02-11 22:23:41 | 0000-00-00 00:00:00 |
|  3 | minnie   | 2010-02-11 23:02:36 | 0000-00-00 00:00:00 |
+----+----------+---------------------+---------------------+
3 rows in set (0.00 sec)

sim:test> UPDATE A  SET word = 'clarabella' WHERE id=3;
Query OK, 1 row affected, 1 warning (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 1

sim:test> SELECT * FROM A;
+----+----------+---------------------+---------------------+
| id | word     | creat               | updated             |
+----+----------+---------------------+---------------------+
|  1 | pippo    | 2010-02-11 22:23:41 | 0000-00-00 00:00:00 |
|  2 | topolino | 2010-02-11 22:23:41 | 0000-00-00 00:00:00 |
|  3 | clarabel | 2010-02-11 23:03:35 | 0000-00-00 00:00:00 |
+----+----------+---------------------+---------------------+
3 rows in set (0.00 sec)</pre>
<p>Robe da pazzi.</p>
<hr/>
<strong>Note:</strong><br />
1) MySQL aggiunge alle funzionalità dell&#8217;SQL (che vorrebbe una sola query per riga) la possibilità di comandi multipli in un solo <em>statement</em>:  ALTER TABLE t2 DROP COLUMN c, DROP COLUMN d;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.simotrone.it/2010/02/23/mysql-e-timestamp-vanno-sulla-luna/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Conversione rapida</title>
		<link>http://www.simotrone.it/2010/02/16/conversione-rapida/</link>
		<comments>http://www.simotrone.it/2010/02/16/conversione-rapida/#comments</comments>
		<pubDate>Tue, 16 Feb 2010 06:56:04 +0000</pubDate>
		<dc:creator>Simotrone</dc:creator>
				<category><![CDATA[Binary People]]></category>
		<category><![CDATA[conversione]]></category>
		<category><![CDATA[Mysql]]></category>
		<category><![CDATA[Perl]]></category>
		<category><![CDATA[tabelle]]></category>

		<guid isPermaLink="false">http://www.simotrone.it/?p=2675</guid>
		<description><![CDATA[Dovevo trasferire rapidamente i dati da una singola tabella in un db MySQL a quattro distinte &#8211; in modo da normalizzare un po&#8217; i dati. Con perl e DBI la cosa viene facile. #!/usr/bin/perl use strict; use DBI; &#91;&#8230;&#93; my $dsn = &#34;dbi:mysql:database=$db_name&#34;; my $dbh = DBI-&#62;connect&#40; $dsn, $username, $password &#41; or die $DBI::errstr; my [...]]]></description>
			<content:encoded><![CDATA[<p>Dovevo trasferire rapidamente i dati da una singola tabella in un db MySQL a quattro distinte &#8211; in modo da <a href="http://en.wikipedia.org/wiki/Database_normalization">normalizzare</a> un po&#8217; i dati.</p>
<p>Con perl e DBI la cosa viene facile.</p>
<div class="codesnip-container" >
<div class="codesnip" style="font-family: monospace;"><span class="co1">#!/usr/bin/perl</span></p>
<p><span class="kw2">use</span> strict;<br />
<span class="kw2">use</span> DBI;<br />
<span class="br0">&#91;</span>&#8230;<span class="br0">&#93;</span><br />
<span class="kw1">my</span> <span class="re0">$dsn</span> = <span class="st0">&quot;dbi:mysql:database=$db_name&quot;</span>;<br />
<span class="kw1">my</span> <span class="re0">$dbh</span> = DBI-&gt;<span class="me1">connect</span><span class="br0">&#40;</span> <span class="re0">$dsn</span>, <span class="re0">$username</span>, <span class="re0">$password</span> <span class="br0">&#41;</span> <span class="kw1">or</span> <a href="http://perldoc.perl.org/functions/die.html"><span class="kw3">die</span></a> <span class="re0">$DBI</span>::<span class="me2">errstr</span>;</p>
<p><span class="kw1">my</span> <span class="re0">$sth</span> = <span class="re0">$dbh</span>-&gt;<span class="me1">prepare</span><span class="br0">&#40;</span><br />
&nbsp; &nbsp; <span class="st0">&#8216;SELECT name, surname, birth, address, cap, city, country, phone, email, notes FROM rubrica&#8217;</span><br />
<span class="br0">&#41;</span> <span class="kw1">or</span> <a href="http://perldoc.perl.org/functions/die.html"><span class="kw3">die</span></a> <span class="re0">$dbh</span>-&gt;<span class="me1">errstr</span>;<br />
<span class="re0">$sth</span>-&gt;<span class="me1">execute</span><span class="br0">&#40;</span><span class="br0">&#41;</span>;</p>
<p><span class="kw1">my</span> <span class="re0">$ins0</span> = <span class="re0">$dbh</span>-&gt;<span class="me1">prepare</span><span class="br0">&#40;</span><br />
&nbsp; &nbsp; <span class="st0">&#8216;INSERT INTO persone (nome,cognome) VALUES (?,?)&#8217;</span><br />
<span class="br0">&#41;</span> <span class="kw1">or</span> <a href="http://perldoc.perl.org/functions/die.html"><span class="kw3">die</span></a> <span class="re0">$dbh</span>-&gt;<span class="me1">errstr</span>;<br />
<span class="kw1">my</span> <span class="re0">$ins1</span> = <span class="re0">$dbh</span>-&gt;<span class="me1">prepare</span><span class="br0">&#40;</span><br />
&nbsp; &nbsp; <span class="st0">&#8216;INSERT INTO indirizzi (id,via,cap,citta,paese) VALUES (?,?,?,?,?)&#8217;</span><br />
<span class="br0">&#41;</span> <span class="kw1">or</span> <a href="http://perldoc.perl.org/functions/die.html"><span class="kw3">die</span></a> <span class="re0">$dbh</span>-&gt;<span class="me1">errstr</span>;<br />
<span class="br0">&#91;</span>&#8230; ecc, seguono altri statement insert &#8230;<span class="br0">&#93;</span></p>
<p><span class="kw1">while</span> <span class="br0">&#40;</span> <span class="kw1">my</span> <span class="re0">$row</span> = <span class="re0">$sth</span>-&gt;<span class="me1">fetchrow_hashref</span><span class="br0">&#40;</span><span class="br0">&#41;</span> <span class="br0">&#41;</span> <span class="br0">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span class="re0">$ins0</span>-&gt;<span class="me1">execute</span><span class="br0">&#40;</span> <span class="re0">$row</span>-&gt;<span class="br0">&#123;</span>name<span class="br0">&#125;</span>, <span class="re0">$row</span>-&gt;<span class="br0">&#123;</span>surname<span class="br0">&#125;</span> <span class="br0">&#41;</span>;<br />
&nbsp; &nbsp; &nbsp; &nbsp; <span class="kw1">my</span> <span class="re0">$rv</span> = <span class="re0">$dbh</span>-&gt;<span class="me1">last_insert_id</span><span class="br0">&#40;</span><a href="http://perldoc.perl.org/functions/undef.html"><span class="kw3">undef</span></a>, <a href="http://perldoc.perl.org/functions/undef.html"><span class="kw3">undef</span></a>, <span class="st0">&#8216;persone&#8217;</span>, <span class="st0">&#8216;id&#8217;</span><span class="br0">&#41;</span>;</p>
<p>&nbsp; &nbsp; &nbsp; &nbsp; <span class="re0">$ins1</span>-&gt;<span class="me1">execute</span><span class="br0">&#40;</span> <span class="re0">$rv</span>, <span class="re0">$row</span>-&gt;<span class="br0">&#123;</span>address<span class="br0">&#125;</span>, <span class="re0">$row</span>-&gt;<span class="br0">&#123;</span>cap<span class="br0">&#125;</span>, <span class="re0">$row</span>-&gt;<span class="br0">&#123;</span>city<span class="br0">&#125;</span>, <span class="re0">$row</span>-&gt;<span class="br0">&#123;</span>country<span class="br0">&#125;</span> <span class="br0">&#41;</span>;<br />
&nbsp; &nbsp; &nbsp; &nbsp; <span class="br0">&#91;</span>&#8230;<span class="br0">&#93;</span><br />
&nbsp;<span class="br0">&#125;</span></div>
</div>
<p>La cosa interessante sta in quel <a href="http://search.cpan.org/~timb/DBI-1.609/DBI.pm#last_insert_id">last_insert_id</a> che raccatta l&#8217;ultimo valore auto incrementato e lo mette in uno scalare, riutilizzabile poi in altri insert per avere le foreign key allineate.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.simotrone.it/2010/02/16/conversione-rapida/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Spostare e confrontare i dati</title>
		<link>http://www.simotrone.it/2010/02/14/spostare-e-confrontare-i-dati/</link>
		<comments>http://www.simotrone.it/2010/02/14/spostare-e-confrontare-i-dati/#comments</comments>
		<pubDate>Sun, 14 Feb 2010 06:39:22 +0000</pubDate>
		<dc:creator>Simotrone</dc:creator>
				<category><![CDATA[Binary People]]></category>
		<category><![CDATA[Mysql]]></category>

		<guid isPermaLink="false">http://www.simotrone.it/?p=2708</guid>
		<description><![CDATA[Dopo qualche ripensamento, ho deciso di spostare alcuni campi che stavano in una tabella (in MySQL) in un&#8217;altra. Come fare in maniera automatica? UPDATE folks SET folks.birth = &#40; SELECT info.birth FROM info WHERE info.id = folks.id&#41;; Se si vuole farlo solo per certe occorrenze, mettere un filtro WHERE in fondo per limitare gli update. [...]]]></description>
			<content:encoded><![CDATA[<p>Dopo qualche ripensamento, ho deciso di spostare alcuni campi che stavano in una tabella (in MySQL) in un&#8217;altra. Come fare in maniera automatica?</p>
<div class="codesnip-container" >
<div class="codesnip" style="font-family: monospace;"><span class="kw1">UPDATE</span> folks <span class="kw1">SET</span> folks.birth = <span class="br0">&#40;</span> <span class="kw1">SELECT</span> info.birth <span class="kw1">FROM</span> info <span class="kw1">WHERE</span> info.id = folks.id<span class="br0">&#41;</span>;</div>
</div>
<p>Se si vuole farlo solo per certe occorrenze, mettere un filtro WHERE in fondo per limitare gli update.</p>
<p>E se si vuole confrontare i dati e vedere se è tutto giusto?</p>
<div class="codesnip-container" >
<div class="codesnip" style="font-family: monospace;"><span class="kw1">SELECT</span> <span class="kw1">IF</span><span class="br0">&#40;</span> STRCMP<span class="br0">&#40;</span>tab1.campo,tab2.campo<span class="br0">&#41;</span>, <span class="nu0">0</span>, <span class="nu0">1</span><span class="br0">&#41;</span> <span class="kw1">FROM</span> tab1 <span class="kw1">JOIN</span> tab2 <span class="kw1">ON</span> tab1.id = tab2.id <span class="kw1">GROUP</span> <span class="kw1">BY</span> campo</div>
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.simotrone.it/2010/02/14/spostare-e-confrontare-i-dati/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>mysqlshow</title>
		<link>http://www.simotrone.it/2010/02/10/mysqlshow/</link>
		<comments>http://www.simotrone.it/2010/02/10/mysqlshow/#comments</comments>
		<pubDate>Wed, 10 Feb 2010 20:29:44 +0000</pubDate>
		<dc:creator>Simotrone</dc:creator>
				<category><![CDATA[Binary People]]></category>
		<category><![CDATA[Mysql]]></category>
		<category><![CDATA[mysqlshow]]></category>

		<guid isPermaLink="false">http://www.simotrone.it/?p=2664</guid>
		<description><![CDATA[Lo sapevo che prima o poi mi avrebbe punito. Ho imparato l&#8217;SQL e i db stando su MySQL, poi sono passato a Pg per varie ragioni (di lavoro ed altro). Mi sono trovato assolutamente bene con Postgre &#8211; pur lottando ogni tanto con la sua macchinosità, e alla fine mi sono ritrovato a non usare [...]]]></description>
			<content:encoded><![CDATA[<p>Lo sapevo che prima o poi mi avrebbe punito.<br />
Ho imparato l&#8217;SQL e i db stando su MySQL, poi sono passato a Pg per varie ragioni (di lavoro ed altro).<br />
Mi sono trovato assolutamente bene con Postgre &#8211; pur lottando ogni tanto con la sua macchinosità, e alla fine mi sono ritrovato a non usare mai MySQL&#8230; fino ad oggi. E ovviamente non mi ricordo (quasi) più nulla.</p>
<p>Poco male, si ricomincia. E due DB <em>is meil che one</em> (almeno finchè ci sono gli ORM come DBIC che capiscon tutto loro).</p>
<p>Mentre pistolavo a casaccio, ho visto che MySQL ha un tot di script da shell che mostrano un po&#8217; di robba, e comunque aiutano se li si impara ad usare.</p>
<pre>$ mysqlshow
+--------------------+
|     Databases      |
+--------------------+
| information_schema |
| agenda             |
| cmsfdt             |
| evento_odg         |
| libri              |
| mail               |
| mysql              |
| studiog7           |
| system_backup      |
| test               |
| test_blog          |
| wines              |
| wp281              |
+--------------------+

$ mysqlshow libri
Database: libri
+---------+
| Tables  |
+---------+
| book    |
| details |
+---------+

$ mysqlshow libri book
Database: libri  Table: book
+---------+-----------+-------------------+------+--
| Field   | Type      | Collation         | Null | ..
+---------+-----------+-------------------+------+--
| id      | int(11)   |                   | NO   | ..
| titolo  | char(100) | latin1_swedish_ci | NO   | ..
| autore  | char(100) | latin1_swedish_ci | NO   | ..
| editore | char(50)  | latin1_swedish_ci | NO   | ..
+---------+-----------+-------------------+------+---
</pre>
<p>A me è parso caruccio.<br />
 <img src='http://www.simotrone.it/wp-includes/images/smilies/icon_razz.gif' alt=':-P' class='wp-smiley' /> </p>
<p>Edit postumo: mysqlshow ha un po&#8217; di opzioni. Una cosa che ho trovato utile è stato usare l&#8217;opzione &#8211;count che dice quante righe ha la tabella richiesta (ho aggiunto in ~/.bashrc alias mysqlshow=&#8217;mysqlshow &#8211;count&#8217;)</p>
]]></content:encoded>
			<wfw:commentRss>http://www.simotrone.it/2010/02/10/mysqlshow/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

