开发者

sql, outer join

I have two tables, linked with an outer join. The relationship between the primary and secondary table is a 1 to [0..n]. The secondary table includes a timestamp column indicating when the record was added. I only want to retrieve the most recent record of the secondary table for each row in the primary. I have to use a group by on the primary table due to other tables also part of the SELECT. There's no way to use a 'having' clause though since this sec开发者_StackOverflowondary table is not part of the group.

How can I do this without doing multiple queries?


For performance, try to touch the table least times

Option 1, OUTER APPLY

SELECT *
FROM
   table1 a
  OUTER APPY
  (SELECT TOP 1 TimeStamp FROM table2 b
   WHERE a.somekey = b.somekey ORDER BY TimeStamp DESC) x

Option 2, Aggregate

SELECT *
FROM
  table1 a
  LEFT JOIN
  (SELECT MAX(TimeStamp) AS maxTs, somekey FROM table2
   GROUP BY somekey) x ON a.somekey = x.somekey

Note: each table is mentioned once, no correlated subqueries


Something like:

SELECT a.id, b.* 
FROM table1 a
INNER JOIN table2 b ON b.parentid = a.id
WHERE b.timestamp = (SELECT MAX(timestamp) FROM table2 c WHERE c.parentid = a.id)

Use LEFT JOIN instead of INNER JOIN if you want to show rows for IDs in table1 without any matches in table2.


select *
from table1 left outer join table2 a on
   table1.id = a.table1_id
where
  not exists (select 1 from table2 b where a.table1_id = b.table1_id and b.timestamp > a.timestamp)


The quickest way I know of is this:

SELECT
  A.*,
  B.SomeField
FROM
  Table1 A
  INNER JOIN (
    SELECT
      B1.A_ID,
      B1.SomeField
    FROM
      Table2 B1
      LEFT JOIN Table2 B2 ON (B1.A_ID=B2.A_ID) AND (B1.TimeStmp < B2.TimeStmp)
    WHERE
      B2.A_ID IS NULL
  ) B ON B.A_ID = A.ID
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜