这是一个开始:
SELECT column_name, substr(column_name,2) AS `index`
FROM information_schema.columns
WHERE table_schema = 'mydatabasename'
AND table_name = 'denormalized_table'
AND column_name REGEXP '^[PD][0-9]+$'
ORDER BY column_name
您可以修改该语句中的选择列表,让 MySQL 为您生成语句:
SELECT CONCAT('INSERT INTO new_table (id, name, `index`) SELECT foreign_key_id, '
,column_name,', ',substr(column_name,2)
,' FROM denormalized_table ;') AS stmt
FROM information_schema.columns
WHERE table_schema = 'mydatabasename'
AND table_name = 'denormalized_table'
AND column_name REGEXP '^[PD][0-9]+$'
ORDER BY column_name
其输出将是一组 MySQL INSERT 语句,然后您可以执行这些语句。
如果要插入的数据的行数和总大小不是太大,您可以并且希望在“一次操作”中完成整个转换,那么您可以生成单个 INSERT INTO ... SELECT 语句,使用 UNION ALL 运算符。我会得到这样的大部分陈述:
SELECT CONCAT('UNION ALL SELECT foreign_key_id, '
,column_name,', ',substr(column_name,2)
,' FROM denormalized_table ') AS stmt
FROM information_schema.columns
WHERE table_schema = 'mydatabasename'
AND table_name = 'denormalized_table'
AND column_name REGEXP '^[PD][0-9]+$'
ORDER BY column_name
我会从中获取输出,并将第一个替换UNION ALL
为INSERT INTO ...
. 这将给我一个运行语句来完成整个转换。