I have a table that uses two identifying columns, let’s call them id and userid. ID is unique in every record, and userid is unique to the user but is in many records.
What I need to do is get a record for the User by userid and then join that record to the first record we have for the user. The logic of the query is as follows:
SELECT v1.id, MIN(v2.id) AS entryid, v1.userid
FROM views v1
INNER JOIN views v2
ON v1.userid = v2.userid
I’m hoping that I don’t have to join the table to a subquery that handles the min() piece of the code as that seems to be quite slow.
I guess (it’s not entirely clear) you want to find for every user, the rows of the table that have minimum
id, so one row per user.In that case, you an use a subquery (a derived table) and join it to the table:
The above can also be written using a Common Table Expression (CTE), if you like them:
Both would be quite efficient with an index on
(userid, id).With SQL-Server, you could write this using the
ROW_NUMBER()window function: