2013-03-01 38 views
0

我有一個具有以下結構和數據的mysql表。我想在任何ID上顯示最後插入的記錄。從MySQL表中獲取最新的更新值

id lc_counter  lc_timestamp 
1  15    2013-03-01 11:54:43 
1  13    2013-03-01 11:48:56 
10 7    2013-03-01 11:54:43 
10 5    2013-03-01 11:48:56 
100 5    2013-03-01 11:54:43 
100 3    2013-03-01 11:54:43 


SELECT inv_id, lc_counter, lc_timestamp 
FROM link_counter 
group by inv_id 
order by inv_id asc, lc_timestamp desc 

我想要得到這樣的結果:

id lc_counter  lc_timestamp 
1  15    2013-03-01 11:54:43 
10 7    2013-03-01 11:54:43 
100 5    2013-03-01 11:54:43 

回答

2
Select link_counter.lc_counter, MAX(link_counter.lc_timestamp) 
from link_counter group by link_counter.id 
0
SELECT 
    inv_id, lc_counter, lc_timestamp 
FROM 
    link_counter A 
WHERE 
    lc_counter >= ALL(
    SELECT 
     lc_counter 
    FROM 
     link_counter B 
    WHERE 
     B.inv_id = A.inv_id 
) 
ORDER BY 
    1 

有一段時間沒有這樣做,而是應該工作。

0

如果您沒有2個相同的lc_timestamp記錄爲特定的id下面將給你你想要的確切結果。

select lc.id, lc.lc_counter, lc.lc_timestamp from link_counter lc inner join 
(select id, max(lc_timestamp) as lc_timestamp from link_counter group by id) as lc2 
on lc.id = lc2.id and lc.lc_timestamp = lc2.lc_timestamp order by lc.id asc, lc.lc_timestamp desc;; 

group by本身不會匹配lc_counter。所以,它需要手動匹配。請參閱此fiddle

+0

Dipesh Parmer's和aaaaaa123456789的回答將返回此數據集的預期結果。但如果數據發生變化(不低估他們的支持),它可能會返回錯誤的值。檢查小提琴中已更改的數據集(交換了lc_timestamp前2個值)。這是我今天能做的最好的。進一步瞭解團隊是如何工作的。這[問題](http://stackoverflow.com/questions/1425240/select-rows-with-maximum-column-value-group-by-another-column)描述了一點。 – chandimak 2013-03-01 12:07:01