MySQL inserts data only if the table does not exist
5 answers
Here's one way to do it:
CREATE TABLE IF NOT EXISTS T (
ID int(10) unsigned NOT NULL primary key,
NAME varchar(255) NOT NULL
);
REPLACE INTO T SELECT 1, 'John Doe';
REPLACE INTO T SELECT 2, 'Jane Doe';
REPLACE is a MySQL extension to the SQL standard that either inserts or deletes and inserts.
0
source to share
Is it possible to store the status of a table as a variable and then use that variable to determine whether to insert data? Example:
@status = SHOW TABLES LIKE 'my_table';
INSERT INTO my_table VALUES (1,'hello'),(2,'world') WHERE @status <> false;
The problem with Paul Morgan is that he expects the data to already exist in another table. Jonas' answer would be extremely resource intensive, especially if there are a lot of REPLACEMENT in there (which are not needed if the table exists).
0
source to share