没有最小值概念的每组第一行对应的select条记录怎么办?

How to select records corresponding to the first row in each group where no concept of minimum exists?

我的table遵循以下结构

+--------+---------+---------------------+--------------------+
| userId | loginId | tstamp              | action             |
+--------+---------+---------------------+--------------------+
| 134088 | NE78MEZ | 2014-10-31 13:59:33 | pageview           |
| 134088 | NE78MEZ | 2014-10-31 13:59:53 | pageview           |
| 134088 | NE78MEZ | 2014-10-31 14:00:26 | pageview           |
| 134088 | NE78MEZ | 2014-10-31 14:00:28 | pageview           |
| 134088 | 9T3CgQ7 | 2014-10-31 14:33:27 | pageview           |
| 134088 | 9T3CgQ7 | 2014-10-31 14:33:27 | pageview           |
| 134088 | 9T3CgQ7 | 2014-10-31 14:46:47 | pageview           |
| 134088 | tq69c8F | 2014-10-31 15:09:02 | pageview           |
| 134088 | tq69c8F | 2014-10-31 15:09:40 | ask                |
| 134088 | tq69c8F | 2014-10-31 15:10:34 | tag                |
| 134088 | tq69c8F | 2014-10-31 15:10:38 | tag                |
| 134088 | tq69c8F | 2014-10-31 15:10:45 | tag                |
| 134088 | tq69c8F | 2014-10-31 15:10:59 | rating             |
| 134088 | tq69c8F | 2014-10-31 15:11:09 | rating             |
| 134088 | tq69c8F | 2014-10-31 15:11:12 | pageview           |
| 134088 | tq69c8F | 2014-10-31 15:11:20 | tag                |
| 134088 | tq69c8F | 2014-10-31 15:11:29 | tag                |
| 134088 | tq69c8F | 2014-10-31 15:13:55 | rating             |
+--------+---------+---------------------+--------------------+

对于每个用户(在下面的示例中我只有一个用户),我有不同的登录 ID,这些登录 ID 是随机生成的 ID,代表不同的登录会话。对于这种随机生成的字符串,minimum(loginId) 的概念没有意义。但是对于每个用户,我想选择与第一个 loginId 对应的所有记录。

所以,我希望输出类似于:

+--------+---------+---------------------+--------------------+
| userId | loginId | tstamp              | action             |
+--------+---------+---------------------+--------------------+
| 134088 | NE78MEZ | 2014-10-31 13:59:33 | pageview           |
| 134088 | NE78MEZ | 2014-10-31 13:59:53 | pageview           |
| 134088 | NE78MEZ | 2014-10-31 14:00:26 | pageview           |
| 134088 | NE78MEZ | 2014-10-31 14:00:28 | pageview           |

对于用户 ID 为 134088 的用户,后面是列表中的下一个用户。

我能想到的一种方法是创建一个名为 session id 的列,它是随机生成的 loginId 的 "numeric" 版本,并使用 where session=1group by userId 子句。有没有一种方法可以在不创建此冗余列的情况下绕过?

我正尝试在 mysql

中执行此操作

您可以通过找到最短时间戳然后选择与之关联的所有登录来完成此操作。使用 window/analytic 函数会容易得多,但在 MySQL:

select t.*
from mytable t join
     (select t2.userid, substring_index(group_concat(t2.loginid order by timestamp), ',', 1) as firstlogin
      from mytable t2
      group by t2.userid
     ) t2
     on t.userid = t2.userid and t.login = t2.firstlogin;

substring_index()/group_concat() 是 MySQL 中的一个技巧,用于获取与第一个时间戳关联的登录。这节省了一些额外的 join 逻辑或必须使用变量。