2016-04-28 11 views
0

2つの表の内部結合があります。他の列で順序付けられた結合の最上行を取得する方法

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

の下に私が得る結果は

であるようなので、私のクエリは見え

表1

sid name 
    1 abc 
    2 xyz 

表2

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

考えてみましょう

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

私は私の最終的な結果は

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

「どのRDBMS」? – Wanderer

答えて

2

のようになります。テーブルから最高の「SDID」を取得するために2

をこのクエリを変更するには、最大を取得するためにjoinに1つのより多くのサブクエリを含めます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 
関連する問題