我们从 ID 作为 int(11) 开始。然后我们切换到 Hibernate 列自动生成,ID 变为 bigint(20)。因此,除非我将连接列定义从 bigint(20) 更改为 int (11),否则许多外键将停止工作。是否可以编写一个脚本将所有列的所有 int(11) 更改为 bigint (20)?
查找所有要更改的列的查询如下:
select table_name, column_name, column_type
from information_schema.columns
where table_schema = 'rentoptimum'
and column_type='int(11)'
order by table_name, ordinal_position;
我可以更新 information_schema.columns 中的数据吗?或者我应该为每个表编写更改脚本?
最佳答案
您可以查询 INFORMATION_SCHEMA
以动态生成一个脚本,其中包含修改这些列数据类型所需的 ALTER TABLE
语句。
您需要非常小心,只能修改数据类型,而不是列的任何其他属性(可空性、自动增量、有符号/无符号等)。
这是一个帮助您入门的示例。这将为给定架构中的每个表生成一个 ALTER TABLE 语句,即使它有多个列需要修改。它将用 bigint(11)
替换 int(11)
,这与您要求的略有不同,但 (11)
不会不影响实际的数据类型。如果您愿意,您可以对其进行调整。
select concat('alter table `',t.table_schema,'`.`',t.table_name,'`',
group_concat(' modify column `',c.column_name,'` ',replace(c.column_type,'int','bigint'),
if(c.is_nullable='yes',' null',' not null '),c.extra),';') as the_ddl
into outfile '/tmp/so42114820.sql'
from information_schema.columns c
inner join information_schema.tables t on t.table_schema = c.table_schema and t.table_name = c.table_name
where t.table_schema = 'your_schema'
and t.table_type = 'BASE TABLE'
and c.data_type = 'int'
group by t.table_schema,t.table_name;
set @foreign_key_checks = @@foreign_key_checks;
set foreign_key_checks = 0;
\. /tmp/so42114820.sql
set foreign_key_checks = @foreign_key_checks;
关于mysql - 如何在 MYSQL 中一次更改多个列的数据类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42114820/