MySql - Create Table If Not Exists Else Truncate?

前端 未结 6 1677
隐瞒了意图╮
隐瞒了意图╮ 2020-12-31 00:23

Here is the updated question:

the current query is doing something like:

$sql1 = \"TRUNCATE TABLE fubar\";
$sql2 = \"CREATE TEMP         


        
6条回答
  •  南笙
    南笙 (楼主)
    2020-12-31 00:34

    shmuel613, it would be better to update your original question rather than replying. It's best if there's a single place containing the complete question rather than having it spread out in a discussion.

    Ben's answer is reasonable, except he seems to have a 'not' where he doesn't want one. Dropping the table only if it doesn't exist isn't quite right.

    You will indeed need multiple statements. Either conditionally create then populate:

    1. CREATE TEMPORARY TABLE IF NOT EXISTS fubar ( id int, name varchar(80) )
    2. TRUNCATE TABLE fubar
    3. INSERT INTO fubar SELECT * FROM barfu

    or just drop and recreate

    1. DROP TABLE IF EXISTS fubar
    2. CREATE TEMPORARY TABLE fubar SELECT id, name FROM barfu

    With pure SQL those are your two real classes of solutions. I like the second better.

    (With a stored procedure you could reduce it to a single statement. Something like: TruncateAndPopulate(fubar) But by the time you write the code for TruncateAndPopulate() you'll spend more time than just using the SQL above.)

提交回复
热议问题