简体   繁体   中英

Is it possible to update multiple rows at the time using Zend_Db_Table?

I have a simple array.

$a = array(
   array('id' => 2, 'year' => 2010),
   array('id' => 3, 'year' => 2011)
);

And i have a MySQL table with id primary key. Now I update my table like this:

foreach ($a as $v) {
  $db->update($v, array('id = ?' => $v['id']));
}

And my $a contains 3700 rows. I need to create one big query instead of loop. How can do it? Thank you in advance. Sorry for my english.

What your asking isn't often done, as you would usually use update() to either set a lot of records to have the same values or set one record to have many differnt values.

One way around this is the aggregate the updates, so using your array get all the ids where the year is 2011 then run this:

 $where = array();

 // This where should contain all the ids that need the year set to 2011
 // E.g.
 $where[] = array("id" => 3);

 $db->update("table_name", array("year" => 2011), $where);

Doing this will reduce the number of queries assuming you have many rows with the same year. The documentation for this is here .

Or you could use a method like this

Edit after OP response

The very nature of the problem means it cannot be solved effeicently.

Your asking for a way of updating 3,700 rows of data with very different sets of data. If the sets of data are different then there is no pattern that you can exploit in order to make this effeicent. Finding patterns, like rows with the same year, and using them to your advantage will increase the speed of the query but will require some brain enagement in the form of array mashing as noted by regilero.

Here's an excellent article on how to update multiple rows quickly and easily . It discusses the approach to collapse multiple update statements to a few statements by aggregating common values to be set in separate arrays, then update each value:

$allIds = array();
foreach ($a as $item) {
    $allIds[$item['year']][] = $item['id'];
}
foreach ($allIds as $year => $ids) {
    $bind = array('year' => $year);
    $where = $db->quoteInto('id IN (?)', $ids);
    $db->update('table_name', $bind, $where);
}

What if there is no or very few common values and the updates can't be collapsed to a few statements? In this case, the article explains the following approach:

  1. Create a temporary table to hold the updates
  2. Populate the temporary table with the updates
  3. Use UPDATE … FROM to update the target table using updates in the temporary table
  4. Use DROP TABLE to drop the temporary table

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM