我有一个mysql表,其中有一列如下:
1
2
3
4
5
6
7
A
B
C
Y
...
我需要将它转换为4列表,如下所示:
| 1 | 2 | 3 | 4 |
| 5 | 6 | 7 | A |
| B | C | Y | ...|
有人可以帮忙吗?
答案 0 :(得分: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;
答案 1 :(得分: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]."')");