I have to do multiple INSERTs of the exact same row except for the recipient field, whose value is different for every row. Short of doing a for/each loop in PHP to INSERT the same row but change the recipient field in every iteration, is there a way to more efficiently go about this in MySQL?
I have to do multiple INSERT s of the exact same row except for
Share
You have a few options. But whether you’ll get the efficiency is something you’ve got to benchmark.
Method 1: First insert all the rows in one batch, then run an update query on a second loop.
I don’t like this approach since the efficiency is lost in trying to run a second set of update queries.
But since you’re going to be using PHP to run the queries, I’d advice method 2.
Method 2:
Build a string to include multiple insert values.
Insert into MyTable (Field1, Field2, … Field-N)
Values (Value1, Value2, Value3, … Value-N),
(Value1, Value2, Value3, … Value-N),
(Value1, Value2, Value3, … Value-N)
You may build the string to a substantial size here. I’ve built it for 10,000 records in the past.
Execute the query by calling the mysql_query function.
Go back to step 1 until you have no more records to insert.
This method is pretty good if you have huge amounts of inserts. But it’s important to keep in mind that a fail in the Insert must be trapped to ensure that the correct records are being inserted. Ideally, a transaction commit would help solve this along with the mysql_affected_rows function.
And finally, if your numbers aren’t so great, build a smaller string. And if your total records is just around fifty or so, just insert them individually.