选择第一行数据块

时间:2015-04-09 16:32:18

标签: mysql sql

我有一张这样的表:

**id - userId - session - time**<br>
1 ---- 1 -------- 1 ----- 20:12:10<br>
2 ---- 1 -------- 1 ----- 20:45:11<br>
3 ---- 1 -------- 1 ----- 20:55:12<br>
4 ---- 2 -------- 1 ----- 10:45:11<br>
5 ---- 2 -------- 1 ----- 10:55:11<br>
6 ---- 1 -------- 2 ----- 05:58:16<br>
7 ---- 1 -------- 2 ----- 05:45:11<br>
8 ---- 1 -------- 2 ----- 05:45:11<br>
...

如何在 mySQL 中仅选择ID为1(仅列会话和时间)的第一行用户,如下所示:

**session - time**<br>
1 -----     20:12:10<br>
2 -----     05:58:16<br><br>

3 个答案:

答案 0 :(得分:1)

如果订单是由id字段给出的,那么你应该获得id最低的行的会话和时间:

SELECT session, time
  FROM your_table
 WHERE id IN (SELECT MIN(id) FROM your_table WHERE userId = 1 GROUP BY session)
 ORDER BY session

编辑,因为我错过了你想要每个会话的第一行。

答案 1 :(得分:-1)

SELECT session, MIN(time) as time
FROM my_table
WHERE userId=1
GROUP BY session

答案 2 :(得分:-1)

我认为&#34; group by&#34;是你的朋友:

mysql> select distinct (userid),session,time from testing;
+--------+---------+------+
| userid | session | time |
+--------+---------+------+
|      1 |       1 | 123  |
|      1 |       1 | 124  |
|      2 |       1 | 124  |
|      2 |       1 | 125  |
|      2 |       3 | 125  |
|      2 |       4 | 125  |
|      3 |       1 | 127  |
+--------+---------+------+
7 rows in set (0.00 sec)

mysql> select userid,session,time from testing group by userid;
+--------+---------+------+
| userid | session | time |
+--------+---------+------+
|      1 |       1 | 123  |
|      2 |       1 | 124  |
|      3 |       1 | 127  |
+--------+---------+------+

希望这有帮助。