我猜(尚不完全清楚)您想为每个用户找到具有 minimum 的表的行id
,因此每个用户一行。
在这种情况下,您可以使用子查询(派生表)并将其连接到表中:
SELECT v.*
FROM views AS v
JOIN
( SELECT userid, MIN(id) AS entryid
FROM views
GROUP BY userid
) AS vm
ON vm.userid = v.userid
AND vm.entryid = v.id ;
如果您喜欢,也可以使用Common Table Expression (CTE)编写上述内容:
; WITH vm AS
( SELECT userid, MIN(id) AS entryid
FROM views
GROUP BY userid
)
SELECT v.*
FROM views AS v
JOIN vm
ON vm.userid = v.userid
AND vm.entryid = v.id ;
两者都将在索引上非常有效(userid, id)
。
使用 SQL-Server,您可以使用ROW_NUMBER()
窗口函数编写此代码:
; WITH viewsRN AS
( SELECT *
, ROW_NUMBER() OVER (PARTITION BY userid ORDER BY id) AS rn
FROM views
)
SELECT * --- skipping the "rn" column
FROM viewsRN
WHERE rn = 1 ;