mysql时间戳比较问题

时间:2017-09-14 07:24:12

标签: mysql greatest-n-per-group

您好我对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并过滤掉最新的一个?

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 |
+-------+----+--------------+--------+-------+---------------------+

3 个答案:

答案 0 :(得分: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 :(得分:0)

您似乎缺少order_by,可以尝试

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

答案 2 :(得分: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