Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple INSERT queries turned into one single query [duplicate]

Tags:

sql

I've searched through Stackoverflow and nothing answers my question properly.

My question is how do you turn multiple INSERT queries into 1 single insert query.

More specific; https://gist.github.com/gregariousjb/e73fdf1489acbbb63651 this one. That's the query I need to understand how to make into a single one.

Sample;

INSERT INTO `creature` (`guid`, `id`, ...) 
     VALUES (1, 2843, ...);
INSERT INTO `creature` (`guid`, `id`, ...)
     VALUES (2, 7853, ...);

There's 1000 of these, that needs to be turned into a single one. I sincerely appreciate any help I can get on this.

like image 753
user2350162 Avatar asked May 05 '13 12:05

user2350162


People also ask

How do I stop inserting duplicate records?

You can use a PRIMARY KEY or a UNIQUE Index on a table with the appropriate fields to stop duplicate records. Let us take an example – The following table contains no such index or primary key, so it would allow duplicate records for first_name and last_name.

Why is my query returning duplicate rows?

If you do not include DISTINCT in a SELECT clause, you might find duplicate rows in your result, because SQL returns the JOB column's value for each row that satisfies the search condition.


3 Answers

If you are using Sql Server try the following

Insert into table (columns..)
Values(values1,value2,...), 
    (values1,value2,...),
    (values1,value2,...),
    (values1,value2,...)
like image 160
Amit Rai Sharma Avatar answered Oct 04 '22 14:10

Amit Rai Sharma


In Mysql, do this (most popular databases have a similar syntax):

INSERT INTO mytable (col1, col2, col3, ...) VALUES
(1, 2843, 0, ...),
(2, 7853, 0, ...);

In most databases, you can do this:

INSERT INTO mytable (col1, col2, col3, ...)
SELECT 1, 2843, 0, ...
UNION ALL
SELECT 2, 7853, 0, ...;

In backward, behind-the-times databases, like Oracle, you must code this second option using the artificial single-rowed table DUAL:

INSERT INTO mytable (col1, col2, col3, ...)
SELECT 1, 2843, 0, ...
FRIM DUAL
UNION ALL
SELECT 2, 7853, 0, ...
FROM DUAL;
like image 27
Bohemian Avatar answered Oct 04 '22 13:10

Bohemian


The closest is the shorthand version that requires the field list only once:

  INSERT INTO `creature` ( <field list> ) VALUES
    ( <value list> ),
    ( <value list> ),
    ( <value list> )
like image 32
Alex K. Avatar answered Oct 04 '22 13:10

Alex K.