mysql为每个用户选择最新的日期行

时间:2015-08-01 03:58:43

标签: mysql

我正在尝试为每个唯一的用户ID选择最近的行,其中pid = 50且active = 1.我无法弄明白。

这是一个示例表

+-----+----------+-------+-----------------------+---------+
| id  | userid   | pid   | start_date            | active  |
+-----+----------+-------+-----------------------+---------+
| 1   | 4        | 50    | 2015-05-15 12:00:00   | 1       |
| 2   | 4        | 50    | 2015-05-16 12:00:00   | 1       |
| 3   | 4        | 50    | 2015-05-17 12:00:00   | 0       |
| 4   | 4        | 51    | 2015-06-29 12:00:00   | 1       |
| 5   | 4        | 51    | 2015-06-30 12:00:00   | 1       |
| 6   | 5        | 50    | 2015-07-05 12:00:00   | 1       |
| 7   | 5        | 50    | 2015-07-06 12:00:00   | 1       |
| 8   | 5        | 51    | 2015-07-08 12:00:00   | 1       |
+-----+----------+-------+-----------------------+---------+

期望的结果

+-----+----------+-------+-----------------------+---------+
| id  | userid   | pid   | start_date            | active  |
+-----+----------+-------+-----------------------+---------+
| 2   | 4        | 50    | 2015-05-16 12:00:00   | 1       |
| 7   | 5        | 50    | 2015-07-06 12:00:00   | 1       |
+-----+----------+-------+-----------------------+---------+

我尝试了很多东西,这是我得到的最接近但不幸的是它并没有放弃。

SELECT *
FROM mytable t1
WHERE
    (
        SELECT COUNT(*)
        FROM mytable t2
        WHERE
            t1.userid = t2.userid           
            AND t1.start_date < t2.start_date
    ) < 1
AND pid = 50
AND active = 1
ORDER BY start_date DESC

1 个答案:

答案 0 :(得分:2)

<强>计划

  
      
  1. 获取用户ID的最后一条记录分组,其中pid为50且处于活动状态
  2.   
  3. 内部联接到mytable以获取与上次
  4. 相关联的记录信息   

<强>查询

select 
my.*
from
(
select userid, pid, active, max(start_date) as lst
from mytable
where pid = 50
and   active = 1
group by userid, pid, active
) maxd
inner join mytable my
on  maxd.userid = my.userid
and maxd.pid    = my.pid
and maxd.active = my.active
and maxd.lst    = my.start_date
;

<强>输出

+----+--------+-----+------------------------+--------+
| id | userid | pid |       start_date       | active |
+----+--------+-----+------------------------+--------+
|  2 |      4 |  50 | May, 16 2015 12:00:00  |      1 |
|  7 |      5 |  50 | July, 06 2015 12:00:00 |      1 |
+----+--------+-----+------------------------+--------+

sqlfiddle

备注

正如@Strawberry建议的那样,更新后也加入了pid和active。这将避免记录不活跃或不是pid 50的可能性,但也会提供完全相同的日期。