2017-09-14 190 views
1

嗨,我曾在MySQL查詢疑問MySQL的時間戳比較問題

mysql> SELECT * from share5; 
+----+-------+--------------+--------+-------+---------------------+ 
| Id | Price | State  | Symbol | Trade | created_date  | 
+----+-------+--------------+--------+-------+---------------------+ 
| 1 | 120 | maharashtra | mh  | buy | 2017-09-12 12:18:11 | 
| 1 | 121 | maharashtra | mh  | buy | 2017-09-12 12:18:36 | 
| 2 | 122 | karnataka | ka  | sell | 2017-09-12 12:19:26 | 
| 2 | 123 | karnataka | ka  | sell | 2017-09-12 12:20:00 | 
| 3 | 124 | tamil nadu | tn  | buy | 2017-09-12 12:20:30 | 
| 3 | 125 | tamil nadu | tn  | buy | 2017-09-12 12:20:43 | 
| 4 | 127 | andrapradesh | ap  | buy | 2017-09-12 12:26:26 | 
| 4 | 126 | andrapradesh | ap  | buy | 2017-09-12 12:26:39 | 
| 4 | 126 | andrapradesh | ap  | buy | 2017-09-12 16:57:19 | 
+----+-------+--------------+--------+-------+---------------------+ 

我想通過比較2個ID對如來選擇指數最新值以上,我想通過比較時間戳來篩選出最新的一個。 我嘗試了下面的一個,但它只給出了第一個不是最新的附加值。 是否可以比較兩個ID並篩選出最新的ID?

mysql> SELECT price,id,state,symbol,trade,created_date from share5 group by id ; 
+-------+----+--------------+--------+-------+---------------------+ 
| price | id | state  | symbol | trade | created_date  | 
+-------+----+--------------+--------+-------+---------------------+ 
| 120 | 1 | maharashtra | mh  | buy | 2017-09-12 12:18:11 | 
| 122 | 2 | karnataka | ka  | sell | 2017-09-12 12:19:26 | 
| 124 | 3 | tamil nadu | tn  | buy | 2017-09-12 12:20:30 | 
| 127 | 4 | andrapradesh | ap  | buy | 2017-09-12 12:26:26 | 
+-------+----+--------------+--------+-------+---------------------+ 
+0

嘗試從share5組中通過id DESC選擇價格,id,狀態,符號,trade,created_date; –

回答

0

從每個組獲得最新的行,你可以使用下面的查詢

select t.* 
from share5 t 
join (
    select Id,max(created_date) created_date 
    from share5 
    group by Id 
) t1 using(Id,created_date) 

DEMO

+1

其工作感謝代碼khalid –

0

好像你缺少ORDER_BY,你可以嘗試

SELECT price,id,state,symbol,trade,created_date from share5 group by id order by created_date desc; 
0

嘗試這個:

SELECT price,id,state,symbol,trade,created_date from share5 where created_date = (select max(created_date)from Customers) group by id,price,state,symbol,trade,created_date