2012-04-06 15 views
9

So come creare una tabella pivot in mysql (vedere l'esempio di codice seguente), ma cosa succede se il numero di colonne nella tabella pivot è molto grande e non voglio digitare 2000 o così tagnames ? - C'è un modo per avere quella lista generata? Molte grazie in anticipo.tabella pivot in mysql

drop table pivot; 
create table pivot SELECT time, 
     max(if(tagname = 'a', value, null)) AS 'a', 
     max(if(tagname = 'b', value, null)) AS 'b', 
     max(if(tagname = 'c', value, null)) AS 'c' 
    FROM test where tagname in ('a','b','c') 
GROUP BY time; 
select * from pivot; 
+3

sguardo a Questo articolo. http://buysql.com/mysql/14-how-to-automate-pivot-tables.html – GeoGo

risposta

1

È sempre possibile creare uno script di shell che fa esattamente questo :-)

#!/bin/sh 

mysql -BN test > /tmp/$$_tagnames.tmp <<SQL 
select distinct tagname from test; 
SQL 

cat > /tmp/$$_create_table.sql <<EOF 
drop table if exists pivot; 
create table pivot select 
EOF 

while read tag; do 
    echo "max(if(tagname = '$tag', value, null)) AS '$tag'," >> /tmp/$$_create_table.sql 
done < /tmp/$$_tagnames.tmp 

cat >> /tmp/$$_create_table.sql <<EOF 
time 
FROM test 
GROUP BY time; 
select * from pivot; 
EOF 

mysql -Bt test < /tmp/$$_create_table.sql 

rm /tmp/$$_create_table.sql 
rm /tmp/$$_tagnames.tmp 

dati:

mysql> select * from test; 
+---------+-------+---------------------+ 
| tagname | value | time    | 
+---------+-------+---------------------+ 
| a  | foo | 2012-12-21 00:00:01 | 
| b  | foo | 2012-04-27 00:00:01 | 
| c  | bar | 2012-03-27 00:00:01 | 
| d  | bar | 2012-12-21 00:00:01 | 
+---------+-------+---------------------+ 
4 rows in set (0.00 sec) 

Script uscita:

$ ./pivot.sh 
+------+------+------+------+---------------------+ 
| a | b | c | d | time    | 
+------+------+------+------+---------------------+ 
| NULL | NULL | bar | NULL | 2012-03-27 00:00:01 | 
| NULL | foo | NULL | NULL | 2012-04-27 00:00:01 | 
| foo | NULL | NULL | bar | 2012-12-21 00:00:01 | 
+------+------+------+------+---------------------+ 
+0

questo è un uso intelligente dello scripting di shell e questo pattern può essere utilizzato anche per altre lingue. –

Problemi correlati