mysql中update和select結(jié)合使用方式
mysql update和select結(jié)合使用
在遇到需要update設(shè)置的參數(shù)來自從其他表select出的結(jié)果時,需要把update和select結(jié)合使用,不同數(shù)據(jù)庫支持的形式不一樣
在mysql中如下:
update A inner join(select id,name from B) c on A.id = c.id set A.name = c.name;
根據(jù)AB兩個表的id相同為條件,把A表的name修改為B的sql語句就如上所示
sql批量更新update嵌套select更新
概述
有兩張表【user】和【city】,user表的 city_uuid
、 city_no
和 city 表的 city_uuid
、 city_no
一一對應(yīng),但是 user 表只有 city_uuid
,這時候需要將 city 對應(yīng)的 city_no
批量更新到 user 表中
批量更新方式
第一種方式(inner join 內(nèi)連接)
update u set u.city_no = c.city_no from user u inner join city c on u.city_uuid = c.city_uuid where u.city_uuid is not null and u.city_no is null
第二種方式(子查詢)
update u set u.city_no = (select c.city_no from city c where u.city_uuid = c.city_uuid) from user u
第三種方式:(笛卡爾積)
update u set u.city_no = c.city_no from [user] u, city c where u.city_uuid = c.city_uuid
update 多表更新
update table1 t1,table2 t2, table3 t3, ... , tablen tn set t1.column= ?, t2.column, t3.column = ?, ... , tn.column = ? where t1.xx= ?, t2.xx = ?, ... , tn.xx = ?
案例:(conditionUuid是user表的外鍵,每個conditionUuid對應(yīng)兩條user記錄,將producter記錄覆蓋consumer記錄的指定字段值)
update r2 set r2.userUuid = r1.userUuid, r2.userName = r1.userName , r2.age = r1.age, r2.updatedTime = '2021-02-22 22:22:22.222' from user r1 inner join user r2 on r1.conditionUuid = r2.conditionUuid where r1.conditionValue = 'condition-consumer-00000000000000000' and r1.userName is not null and r2.conditionValue = 'condition-producter-0000000000000000' and r2.userName is not null
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
MySQL中參數(shù)sql_safe_updates在生產(chǎn)環(huán)境的使用詳解
這篇文章主要給大家介紹了關(guān)于MySQL中參數(shù)sql_safe_updates在生產(chǎn)環(huán)境使用的相關(guān)資料,并給大家分享了解決mysql sql_safe_updates不支持子查詢更新的方法,分享出來供大家參考學習,需要的朋友們下面來一起看看吧。2017-11-11關(guān)于Mysql-connector-java驅(qū)動版本問題總結(jié)
這篇文章主要介紹了Mysql-connector-java驅(qū)動版本問題,本文給大家介紹的很詳細,通過原因說明問題小結(jié)個人建議給大家展示的很好,需要的朋友可以參考下2021-06-06MySQL定時備份數(shù)據(jù)庫(全庫備份)的實現(xiàn)
本文主要介紹了MySQL定時備份數(shù)據(jù)庫(全庫備份)的實現(xiàn),文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-09-09