MySQL:使用MIN和GROUP BY

时间:2017-02-03 03:34:00

标签: mysql group-by having

表格包含以下数据 每个相同的ID都具有相同的日期时间。

ID |     sendtime  |  gcm  | type
1, 2010-07-14 12:12:12, 1111111,  a
1, 2010-07-14 12:12:12, 2222222,  b
1, 2010-07-14 12:12:12, 3333333,  c
2, 2010-07-10 11:11:11, 4444444,  d
2, 2010-07-10 11:11:11, 5555555,  c
3, 2010-07-15 13:13:13, 6666666,  b
4, 2010-07-14 14:14:14, 7777777,  a

我希望获得

之后的值
ID |     sendtime  |  gcm  | type
2, 2010-07-10 11:11:11, 4444444,  d
2, 2010-07-10 11:11:11, 5555555,  c

结果意味着获取具有相同ID和COUNT(*)>的所有行。 1和MIN(日期时间)。

我尝试了以下查询。

SELECT *
FROM USER a INNER JOIN
     (SELECT ID, MIN(sendtime)
      FROM USER
      GROUP BY ID
      HAVING COUNT(*) > 1
     ) b
     ON a.ID = b.ID;

但结果是

1, 2010-07-14 12:12:12, 1111111,  a
1, 2010-07-14 12:12:12, 2222222,  b
1, 2010-07-14 12:12:12, 3333333,  c
2, 2010-07-10 11:11:11, 4444444,  d
2, 2010-07-10 11:11:11, 5555555,  c

如何获得正确的价值?

2 个答案:

答案 0 :(得分:0)

这是表达逻辑的一种方式:

select u.*
from user u
where u.sendtime = (select min(u2.sendtime) from user u2 where u2.id = u.id
                   ) and
      (select count(*)
       from user u2
       where u2.id = u.id and u2.sendtime = u.sendtime
      ) >= 2;

答案 1 :(得分:0)

我解决了这项工作。

选择a。* 来自用户内部加入      (SELECT FROM FROM USER       GROUP BY ID       有计数(*)> 1       按订单排序ASC限制1      )b      ON a.ID = b.ID;