adding column to all tables in a mysql database (unknown table names)

前端 未结 4 824
予麋鹿
予麋鹿 2021-02-08 08:49

I need to add a primary key to a set of tables in a given database. I do not know how many tables there will be or what their specific names are. They will all be of the for dat

4条回答
  •  清酒与你
    2021-02-08 09:13

    If you want to fully script this, you can do something like this:

    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
    

提交回复
热议问题