SQL选择加入并需要最后一条记录

时间:2011-04-15 19:18:45

标签: sql join max

我有以下表格:

devices table
SN     tested_device_id  test_setup_id  

129    6      103  
129    7      104   
130    8      106

test_setup table
test_setup_id data1  
103 111  
104 333  
106 555  

我想为每个

的最后一个实例提供SN,test_setup_id,data1
serial number as follows:  
129,104,333   
130,106,555  

(省略SN 129的早期副本)。

我有一个如下查询,它提供了SN 129的两个记录,并且不知道如何调整它只传递最后一个:

SELECT sn, 
       test_setup_id, 
       data1 
FROM   test_setup 
       INNER JOIN devices 
         ON test_setup.test_setup_id = devices.test_setup_id 

欢迎任何协助。谢谢。

3 个答案:

答案 0 :(得分:1)

试试这个

SELECT d.sn, 
       d.test_setup_id, 
       ts.data1 
FROM   (SELECT d.sn, 
               MAX(d.test_setup_id) test_setup_id 
        FROM   devices d 
        GROUP  BY d.sn) maxsetupid 
       INNER JOIN devices d 
         ON maxsetupid.test_setup_id = d.test_setup_id 
       INNER JOIN test_setup ts 
         ON d.test_setup_id = ts.test_setup_id 

答案 1 :(得分:0)

SELECT
  d.SN, d.test_setup_id, ts.data1
FROM devices d
  LEFT JOIN devices d2 ON d.SN = d2.SN and d.test_setup_id < d2.test_setup_id
  INNER JOIN test_setup ts ON d.test_setup_id = ts.test_setup_id
WHERE d2.SN IS NULL

答案 2 :(得分:-1)

如果test_setup_id总是递增,您可以执行以下操作:

SELECT sn, 
       test_setup_id, 
       data1 
FROM   test_setup 
       INNER JOIN devices 
         ON test_setup.test_setup_id = devices.test_setup_id 
WHERE  test_setup_id = (SELECT MAX(test_setup_id) 
                        FROM   test_setup)