mysql批量更新多個字段不一樣值

今天作項目需求發現一個比較好用的單條SQL語句mysql批量更新數據庫.php

CASE  WHEN  THEN  END mysql

//還原城市原有排序
            $ids = '';
            $sql = "UPDATE ffan_cities SET asort = CASE cityId ";
            foreach ($showCities as $k => $v) {
                $sql .= sprintf("WHEN %d THEN %d ", $v['cityId'], $v['asort']);
                $ids .= $v['cityId'].',';
            }
            $ids = trim($ids,',');
            $sql .= "END WHERE cityId IN ($ids)";
            $res = $this->execute($sql);

看上面代碼,最後一句代碼執行SQL語句,前面都是組織好SQL語句準備的.最得出這樣一條SQL:sql

UPDATE ffan_cities數據庫

SET asort = CASE cityId this

WHEN 11023 THEN 3code

WHEN 11024 THEN 7 排序

ENDci

WHERE cityId IN (11023,11024)it

 這條SQL很好理解,條件當cityId=11023時 asort更新爲3,後面的類推,最後where條件 cityId IN 這個組裏邊爲了提升執行效率.class

還有個能夠批量更新多個字段的語句,你們能夠看看.(網上找的例子,其實都差很少)

UPDATE categories      SET display_order = CASE id          WHEN 1 THEN 3          WHEN 2 THEN 4          WHEN 3 THEN 5      END,      title = CASE id          WHEN 1 THEN 'New Title 1'         WHEN 2 THEN 'New Title 2'         WHEN 3 THEN 'New Title 3'     END WHERE id IN (1,2,3)

相關文章
相關標籤/搜索