2010-11-09 120 views
1

我有一個事務日誌表,每次更新記錄時都會更新。更新涉及groupby子句的表,同時避免臨時表

autoid ID Date  Source 
1  1 2010-10-11 abc 
2  2 2010-09-10 xyz 
3  1 2010-08-03 pqr 
4  1 2010-11-01 mno 

我能獲得最新通過以下查詢每個ID更新(它是有效的,是嗎?):

select * from mytable group by ID order by Date desc; 

現在,如果我有應與被更新的另一個表最近的交易日期,如何在不創建臨時表的情況下執行此操作?

以下查詢不正確,但有沒有嵌套的查詢替代?我不想創建臨時表。

update mytable a, othertable b 
set b.date = a.date 
where b.ID = a.ID group by ID order by Date desc; 

艾傑瑞爾的解決方案工作!

update othertable, 
(select b.id, max(b.`date`) as latest from mytable b group by b.id) as b 
set othertable.`date` = b.latest 
where othertable.id=b.id 
; 
+0

加入指數ID +日期應該幫助, 不知道表的大小和u似乎SELECT *無極限......是一種效率不高,UPDATE語句是錯誤的原因在GROUP BY中缺少表別名 – ajreal 2010-11-09 21:00:08

+0

我正在處理的這個表返回700行,因此沒有限制。所以一個表別名應該使更新查詢工作組?你能否提出一個示例查詢?我通常不用複雜的查詢,但臨時表是我討厭的東西! – ThinkCode 2010-11-09 21:04:33

回答

1
update mytable, 
(select b.id, max(b.`date`) as latest from othertable b group by b.id) as b 
set mytable.`date`=b.latest 
where mytable.id=b.id 
; 
+0

我試過這個,但它是拋出一個錯誤。我不得不用mytable替換mytable,因爲我正在用mytable的數據更新其他表。 – ThinkCode 2010-11-09 21:49:55

+0

create table mytable(autoid integer primary key auto_increment,id integer,'date' date,source varchar(3)); (10,curdate() - 1,'test'),(11,curdate() - 5,'test'),(10,curdate() - )將插入mytable(id,'date', 3, '測試'); 創建表格,如mytable; (10),(11);插入到其他(id)值(10),(11); – ThinkCode 2010-11-09 21:50:11

+0

注意幾個問題1. curdate() - n可以替換爲date_add(curdate(),interval n天)2.源的字符長度太小 – ajreal 2010-11-09 22:00:48