數據庫_基礎知識_MySQL_UpdateSelect(根據查詢出來的結果批量更新)


有兩個表:SPEC1、tmpDOT
SPEC1種一列為:HIGH
tmpDOT共有兩個:OLD、NEW
兩個表的內容大概如下:
SPEC1:
... HIGH ...
... A    ...
... B    ...
... A    ...
... C    ...
... B    ...
... D    ...

tmpDOT:
OLD   NEW
A     newA
B     newB

C     newC

方法一

[html]  view plain  copy
  在CODE上查看代碼片 派生到我的代碼片
  1. update a set HIGH=b.NEW  from SPEC1 a,tmpDOT  b   
  2. where a.high=b.old  


方法二

[html]  view plain  copy
  在CODE上查看代碼片 派生到我的代碼片
  1. UPDATE A  
  2. SET HIGH=B.NEW  
  3. FROM A LEFT JOIN B ON (A.HIGH=B.OLD)  


一個復雜的栗子:一個更新多個字段的例子


UPDATE A JOIN B ON A.XX= B.XX

SET A.Y = B.Y,   A.Z=B.Z


-- 正式版本 最終版 統計上班排名和時間
UPDATE mobile_user_total AS old
INNER JOIN
(
SELECT u_info.user_id, class.class_name, u_info.`name`, a.clock_date AS arrive_time, COUNT(b.user_id)+1 AS up_rank
FROM user_info u_info
JOIN user_class u_class ON u_info.user_id = u_class.user_id
JOIN class ON class.id = u_class.class_id
JOIN
# a 表作為考勤主表用來統計用戶沒有遲到的最早記錄
(
SELECT u_clock.user_id, MIN(clock_date) AS clock_date, u_class.class_id
FROM user_clockrecords u_clock
JOIN user_class u_class ON u_class.user_id = u_clock.user_id
JOIN class ON u_class.class_id = class.id
WHERE DATE(clock_date) = cal_date AND DATE_FORMAT(u_clock.clock_date,'%H:%i:%s') < DATE_FORMAT(class.begin_time,'%H:%i:%s') #根據傳入的日期
GROUP BY user_id
)AS a ON u_info.user_id = a.user_id
LEFT JOIN(
SELECT u_clock.user_id, MIN(clock_date) AS clock_date, u_class.class_id
FROM user_clockrecords u_clock
JOIN user_class u_class ON u_class.user_id = u_clock.user_id
JOIN class ON u_class.class_id = class.id
WHERE DATE(clock_date) = cal_date AND DATE_FORMAT(u_clock.clock_date,'%H:%i:%s') < DATE_FORMAT(class.begin_time,'%H:%i:%s') #根據傳入的日期
GROUP BY user_id
)AS b ON a.class_id = b.class_id AND u_info.user_id <> b.user_id AND b.clock_date < a.clock_date
GROUP BY u_info.user_id
)AS new ON old.user_id = new.user_id AND old.`current_time` = cal_date #根據傳入的日期
SET old.work_clock_time = new.arrive_time, old.up_ranking = new.up_rank;



方法三

[html]  view plain  copy
  在CODE上查看代碼片 派生到我的代碼片
  1. update  a  
  2.   set high  = (select new from tmpdot where old=a.high  )  
  3.    from spec1 a  







注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
粤ICP备14056181号  © 2014-2020 ITdaan.com