我有一个 mysql 表,其中有一列是这样的:
1
2
3
4
5
6
7
A
B
C
Y
...
我需要将它转换成一个 4 列的表,如下所示:
| 1 | 2 | 3 | 4 |
| 5 | 6 | 7 | A |
| B | C | Y | ...|
有人可以帮忙吗?
我有一个 mysql 表,其中有一列是这样的:
1
2
3
4
5
6
7
A
B
C
Y
...
我需要将它转换成一个 4 列的表,如下所示:
| 1 | 2 | 3 | 4 |
| 5 | 6 | 7 | A |
| B | C | Y | ...|
有人可以帮忙吗?
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;
如果你有 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]."')");