-7

我有一个 mysql 表,其中有一列是这样的:

1
2
3
4
5
6
7
A
B
C
Y
...

我需要将它转换成一个 4 列的表,如下所示:

|  1 |  2 |  3 |  4 |
|  5 |  6 |  7 |  A |
|  B |  C |  Y | ...|

有人可以帮忙吗?

4

2 回答 2

6
ALTER TABLE tbl 
    ADD COLUMN col1 CHAR(1),
    ADD COLUMN col2 CHAR(1),
    ADD COLUMN col3 CHAR(1),
    ADD COLUMN col4 CHAR(1);

SET @rn = 0;

INSERT INTO tbl (col1, col2, col3, col4)
SELECT SUBSTRING(GROUP_CONCAT(a.col ORDER BY a.rn), 1, 1),
       SUBSTRING(GROUP_CONCAT(a.col ORDER BY a.rn), 3, 1),
       SUBSTRING(GROUP_CONCAT(a.col ORDER BY a.rn), 5, 1),
       SUBSTRING(GROUP_CONCAT(a.col ORDER BY a.rn), 7, 1)
FROM   (
       SELECT col, @rn:=@rn+1 AS rn
       FROM   tbl
       ) a
GROUP BY CEIL(a.rn / 4);

ALTER TABLE tbl DROP COLUMN col;

DELETE FROM tbl 
WHERE col1 IS NULL AND 
      col2 IS NULL AND
      col3 IS NULL AND 
      col4 IS NULL;

SQLFiddle 演示

于 2012-08-04T23:43:29.870 回答
0

如果你有 php,你可以尝试这样的事情:

$q=mysql_query('select col from table');
while ($a=mysql_fetch_assoc($q){
    $c[]=$a['col'];
}
for ($i=0;$d[]=array_slice($c,$i,4););
foreach($d as $k => $v)
  mysql_query("insert into bullsh values('".$v[0]."','".$v[1]."','".$v[2]."','".$v[3]."')");
于 2012-08-04T23:36:31.317 回答