将列添加到mysql数据库中的所有表(未知表名)

PFr*_*ise 11 mysql database primary-key

我需要将一个主键添加到给定数据库中的一组表.我不知道会有多少个表或者它们的具体名称是什么.它们都是for datatable _ ##,其中##将根据我的脚本运行的各个位置而变化.

要添加主键,我使用此查询:

alter table datatable_??
add column ID int auto_increment not null first,
add primary key (ID);
Run Code Online (Sandbox Code Playgroud)

所以,我需要在数据库中的每个表上运行它.看起来我可以在PHP脚本或其他东西中做到这一点,但是它们是一种更简单的方法来在sql脚本中执行此操作吗?

Ike*_*ker 23

如果你想完全编写脚本,可以这样做:

SELECT CONCAT('ALTER TABLE ',
table_schema,
'.',
table_name,
' ADD COLUMN id INT AUTO_INCREMENT NOT NULL PRIMARY KEY FIRST;') AS ddl
INTO OUTFILE '/tmp/alter_table.sql'
FROM information_schema.tables
WHERE table_schema = 'db_name' 
AND table_type = 'base table';

\. /tmp/alter_table.sql
Run Code Online (Sandbox Code Playgroud)


Nic*_*ssu 15

select concat('alter table ',table_name,' add column ID int auto_increment not null primary key first;')
from information_schema.tables
where table_schema = 'db_name' and table_type = 'base table';
Run Code Online (Sandbox Code Playgroud)

获得输出后,复制并粘贴并运行它们.

  • 您还可以通过使用"SELECT INTO OUTFILE"将DDL命令写入脚本来避免复制和粘贴步骤,然后使用该脚本来执行命令. (3认同)