2012-04-17 72 views
0

我有兩個表:SQL:將更新與組合更新?

events

mac | na 
---------- 
abc | (null) 
abc | (null) 
def | (null) 

enrichments

mac | na | timestamp 
--------------------- 
abc | na1 | 1 
abc | na2 | 2 
abc | na3 | 3 
def | na4 | 1 

現在我想在enrichments.na更新events.na列與值,其中mac比賽,並timestamp是該特定mac的最大timestamp

在這個例子中,結果將是:

abc | na3 
abc | na3 
def | na4 

什麼是做到這一點的最有效方法是什麼?

謝謝!

+1

您正在使用什麼數據庫工作? – 2012-04-17 08:37:07

+0

這將是HyperSQL(HSQLDB)。 – 2012-04-17 08:52:28

+1

爲什麼你在表'events'中有兩個相同的行? – 2012-04-17 09:10:35

回答

1
UPDATE events AS e 
SET na = 
    (SELECT n.na 
     FROM enrichments AS n 
     WHERE n.mac = e.mac 
     ORDER BY n.timestamp DESC 
     FETCH FIRST 1 ROWS ONLY 
    ) 
+0

感謝您的鏈接到正確的手冊。我沒有看到解釋數據庫系統的意見,因爲我正在寫我的答案。 – 2012-04-17 09:43:13

+0

@AndriyM:你爲什麼要刪除你的答案。它可能工作正常。 – 2012-04-17 09:48:40

+0

因爲它基本上和你的一樣,只是我不知道正確的語法(因爲我不知道OP使用什麼產品)。你已經很好地搜索了正確的手冊,所以你的答案應該留下來。 – 2012-04-17 09:50:33

1

這應該與SQL Server使用公共表表達式

create table events (mac nvarchar(3), na nvarchar(3)) 
insert into events values ('abc',null); 
insert into events values ('abc',null); 
insert into events values ('def',null); 

create table enrichments (mac nvarchar(3), na nvarchar(3), timestamp int) 
insert into enrichments values ('abc','na1',1) 
insert into enrichments values ('abc','na2',2) 
insert into enrichments values ('abc','na3',3) 
insert into enrichments values ('def','na4',1) 

with latestEnrichment (mac, latestTimestamp) as 
    (select mac, MAX(timestamp) 
    from enrichments 
    group by mac) 
update events 
set  na = en.na 
from events e join enrichments en on e.mac = en.mac 
     join latestEnrichment le on en.timestamp = le.latesttimestamp and 
     en.mac = le.mac