从SQL中的时间戳获取第一个日期

时间:2016-03-07 10:06:14

标签: mysql sql moodle

对于每个db tablesession,我都在我的Moodle sessid timestart中。该表如下所示:

+----+--------+------------+
| id | sessid | timestart  |
+----+--------+------------+
|  1 |      3 | 1456819200 |
|  2 |      3 | 1465887600 |
|  3 |      3 | 1459839600 |
|  4 |      2 | 1457940600 |
|  5 |      2 | 1460529000 |
+----+--------+------------+

如何从every的{​​{1}}获取session first date timestamps

3 个答案:

答案 0 :(得分:2)

您可以轻松使用:

select sessid,min(timestart) FROM mytable GROUP by sessid;

对于你的第二个问题,这样的事情:

SELECT
  my.id,
  my.sessid,
  IF(my.timestart = m.timestart, 'yes', 'NO' ) AS First,
  my.timestart
FROM mytable my
LEFT JOIN 
  (
    SELECT sessid,min(timestart) AS timestart FROM mytable GROUP BY sessid
  ) AS m ON m.sessid = my.sessid;

答案 1 :(得分:0)

<强>查询

select sessid, min(timestart) as timestart
from your_table_name
group by sessid;

如果你甚至需要id,那么只是另一个视角。

select t.id, t.sessid, t.timestart from
(
    select id, sessid, timestart, 
    (
        case sessid when @curA 
        then @curRow := @curRow + 1 
        else @curRow := 1 and @curA := sessid end 
    ) as rn 
    from your_table_name t, 
    (select @curRow := 0, @curA := '') r 
    order by sessid,id
)t
where t.rn = 1;

答案 2 :(得分:0)

试试这个。

SELECT
    *
FROM 
    tbl 
WHERE
    (sessid, timestart) IN (
        SELECT tbl2.sessid, MIN(tbl2.timestart) 
        FROM tbl tbl2 
        WHERE tbl.sessid = tbl2.sessid
    );