【问题标题】:How to get the top row in join which is ordered by another column如何获取由另一列排序的连接中的第一行
【发布时间】:2016-04-28 21:22:28
【问题描述】:

我在 2 个表上有一个内部联接。

考虑

表1

   sid   name
    1   abc
    2   xyz

表2

sdid sid detailname
1     1    a
2     1    b
3     2    x

所以我的查询如下所示

SELECT *
FROM table1 t1
INNER JOIN table2 t2
ON t1.sid=t2.sid

我得到的结果是

sid  name   sdid    sid  detailname
1     abc    1       1      a
1     abc    2       1      b
2     xyz    3       2      x

我想修改此查询以从表 2 中获取最高的 'sdid'

我的最终结果应该是这样的

sid    name   sdid    sid  detailname 
1       abc    2       1      b
2       xyz    3       2      x

【问题讨论】:

    标签: sql join


    【解决方案1】:

    join 中再包含一个子查询,以从 table2 中获取每个 sid 的最大 sdid。

    SELECT t1.sid,t1.name,t2.sdid,t2.sid,t2.detailname
    FROM table1 t1
    INNER JOIN table2 t2 ON t1.sid=t2.sid
    INNER JOIN (select max(sdid) as maxsdid, sid from table2 group by sid) t21 
    ON t21.sid=t2.sid and t21.sdid = t2.sdid
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-09
      • 1970-01-01
      • 1970-01-01
      • 2019-10-17
      • 1970-01-01
      • 2011-01-30
      相关资源
      最近更新 更多