views:

73

answers:

1

I'm looking for the fastest way to insert multiple rows in a MySql table with two columns. One column has a constant value (1 for example) while the other always changes.

I am using php and i have a large string with email addresses (thousands), i want to put it in a table with the columns: email_cat_id and email_address. The email_cat_id is constant while the email_address change for every email.

+1  A: 

It should be possible to insert multiple rows in one statement with something like this:

INSERT INTO [table] 
( [col1], [col2] ) VALUES 
( '[data for col1]', '[data for col2]' ), 
( '[data (2nd row) for col1]', '[data (2nd row) for col2]' ), 
...

Has the fixed column always the same value upon insertion? If so, you should set a default value for that column and omit its value in the insert statement.

If you need to insert A LOT of records, you should also check out the LOAD DATA INFILE command. This lets you bulk-import data from a text file, but it can be invoked like any other SQL command. (For more, see MySQL-documentation at http://dev.mysql.com/doc/refman/5.1/en/load-data.html)

Malte
the is nothig possible to do so i don't have to explode the string?
TrustWeb
You'll have to split it at some point; either using `explode()`, or by using some sort of complicted string manipulation logic on the database, or by parsing the input while you read it, and shoot values into the database one by one. Databases aren't good at string manipulation, so the second option isn't your best bet. The third one is best suited if your dataset is very large.
tdammers
Where do you get your email adresses from in the first place? If they are imported with a form field one per line, you could directly save this data to a temporary file and then use LOAD DATA INFILE - no explode() necessary. Also, check out http://dev.mysql.com/doc/refman/5.1/en/insert-speed.html!
Malte