简体   繁体   中英

possible to join a table on only one row

I have a temporary table I'm creating in a sproc that houses my user information. I need to join this table to another table that has SEVERAL rows for that particular user but I only want to return one result from the "many" table.

something like this

SELECT u.firstname, u.lastname
FROM #users AS u
INNER JOIN OtherTable AS ot on u.userid = (top 1 ot.userid)

obviously that wont' work but that's the gist of what I'm trying to do for two reasons, one I only want one row returned (by a date field descending) and two for optimaztion purposes. The query has to scan several thousand rows as it currently is..

SELECT
   u.firstname, u.lastname, t.*
FROM
   #users AS u
   CROSS APPLY
   (SELECT TOP 1 * 
    FROM OtherTable AS ot 
    WHERE u.userid = ot.userid
   ORDER BY something) t

Use the ROW_NUMBER() function to order your rows by datetime and then filter by row_num = 1

;WITH otNewest
AS
(
    SELECT * 
    FROM othertable  
    WHERE ROW_NUM() OVER(partition by userid order by datetime DESC) = 1
)
SELECT u.firstname, u.lastname, o.*
FROM #users U
INNER JOIN otNewest O
    ON U.userid = O.userid

So, if you're joining but not returning any columns from OtherTable , then you're only interested in checking for existence?

SELECT u.firstname, u.lastname 
    FROM #users AS u 
    WHERE EXISTS(SELECT 1
                     FROM OtherTable ot
                     WHERE u.userid = ot.userid)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM