简体   繁体   中英

MySQL: IF table exists, truncate and insert ELSE create

Working only with MySQL (I have essentially no PHP knowledge), I need to have a table that's essentially a subset from a much larger table. The source table changes from time to time, losing some entries, gaining other new ones, and values changing for existing ones. I can describe what I want to happen, but can't seem to figure out a syntax of commands to make it work. I also know I can have two separate queries and just run whichever one I need, and I have that worked out, but I'd like to combine them if possible. Here's what I want:

IF the subset_table DOES NOT EXIST, create it as [select query], ELSE truncate the subset_table and insert [select query]

Like I said, I know there are other ways to do this - I could drop if exists/create, or I could just have two different sql files to run. I just want to know if I can do this as specified above.

Thoughts?

You can do this:

create table if not exists <tablename> . . .;

truncate table <tablename>;

insert into <tablename>(cols)
    select blah blahblah . . .;

You don't need any if statements at all.

This can also be done through an SP (stored procedure)... makes it more readable and safe

DELIMITER $$

    DROP PROCEDURE IF EXISTS `create_table_sp`$$

    CREATE PROCEDURE `create_table_sp`()
    BEGIN

    IF NOT EXISTS (SELECT 1 FROM information_schema.TABLES WHERE table_name = '<table_name>'
    AND table_schema = DATABASE() AND table_type = 'BASE TABLE') THEN
        CREATE TABLE <subset_table_name>
        AS SELECT * FROM <main_table_name>;
    ELSE
        TRUNCATE TABLE <subset_table_name>;
        INSERT INTO <subset_table_name>
        AS SELECT * FROM <main_table_name>;
    END IF;

    END$$

    DELIMITER ;

    CALL `create_table_sp`;

DROP PROCEDURE IF EXISTS `create_table_sp`;

There is also another way,

  • You could pass the table names as arguments to the SP, in this case sub_table_name and main_table_name
  • Make the above DML statements to a string using CONCAT()
  • Create a prepared statement out of it and execute

Hope this helped....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM