Alter table if exists or create if doesn't

后端 未结 2 1055
春和景丽
春和景丽 2020-12-10 01:08

I need to run an installer which can also be an updater. The installer needs to be able to end up having a certain scheme/structure of the mysql database, regardless if some

相关标签:
2条回答
  • 2020-12-10 01:56

    Well if you are using a coding language do:

    SHOW TABLES LIKE 'myTable'
    

    if it return a value call the alter else call the create

    0 讨论(0)
  • 2020-12-10 01:59

    MySQL INFORMATION_SCHEMA database to the rescue:

    -- First check if the table exists
    IF EXISTS(SELECT table_name 
                FROM INFORMATION_SCHEMA.TABLES
               WHERE table_schema = 'db_name'
                 AND table_name LIKE 'wild')
    
    -- If exists, retreive columns information from that table
    THEN
       SELECT COLUMN_NAME, DATA_TYPE, IS_NULLABLE, COLUMN_DEFAULT
         FROM INFORMATION_SCHEMA.COLUMNS
        WHERE table_name = 'tbl_name'
          AND table_schema = 'db_name';
    
       -- do some action, i.e. ALTER TABLE if some columns are missing 
       ALTER TABLE ...
    
    -- Table does not exist, create a new table
    ELSE
       CREATE TABLE ....
    
    END IF;
    

    More information:

    • MySQL Reference Manual: Chapter 19. INFORMATION_SCHEMA Tables
    • MySQL Reference Manual: The INFORMATION_SCHEMA TABLES Table
    • MySQL Reference Manual: The INFORMATION_SCHEMA COLUMNS Table

    UPDATE:

    Another option, possibly easier, is to drop the existing table and re-create it again with the new schema. To do this, you need:

    1. Create temporary table, an exact copy of the existing table
    2. Populate the temporary table with the data from the old table
    3. Drop the old table
    4. Create the new table with new schema
    5. Populate the new table with the information from the temporary table
    6. Drop temporary table.

    So, in SQL code:

    CREATE TABLE old_table_copy LIKE old_table;
    
    INSERT INTO old_table_copy
    SELECT * FROM old_table;
    
    DROP TABLE old_table;
    
    CREATE TABLE new_table (...new values...);
    
    INSERT INTO new_table ([... column names from old table ...])
    SELECT [...column names from old table ...] 
    FROM old_table_copy;
    
    DROP TABLE old_table_copy;
    

    Actually the last step, "Drop temporary table.", you could skip for a while. Just in case, you would want to have some sort of backup of the old table, "just-in-case".

    More information:

    • MySQL Reference Manual: CREATE TABLE Syntax
    • MySQL Reference Manual: INSERT Syntax
    • MySQL Reference Manual: INSERT ... SELECT Syntax
    0 讨论(0)
提交回复
热议问题