3

假设我们有一个名为 table A 的表

id         foreign_id   value
1             1         x
2             2         y
3             1         y
4             2         x
5             3         x

id主键在哪里

您如何获得id按外国 id 分组的最新行(我们将按照 的顺序进行排序)?基本上,我想要得到的是

id     foreign_id     value
3      1              y
4      2              x
5      3              x  
4

4 回答 4

3

试试这个查询,

SELECT t.id, t.foreign_id, t.value FROM #temp t
WHERE t.id IN (SELECT max(id) FROM #temp GROUP BY foreign_id)

替换#temp为您的实际表名。

于 2013-03-14T09:23:47.473 回答
2

试试这个查询

SELECT max(id) AS ID, foreign_id FROM tbl
GROUP BY  foreign_id

如果还需要价值,那么

SELECT a.ID, a.foreign_id, a.value  
FROM tbl a,
(SELECT max(id) AS ID, foreign_id 
        FROM tbl GROUP BY foreign_id) b
WHERE a.id = b.id AND 
      a.foreign_id = b.foreign_id

小提琴

于 2013-03-14T09:16:54.610 回答
0
SELECT  a.*
FROM    tableName a
        INNER JOIN
        (
            SELECT  foreign_ID, max(id) max_ID
            FROM    tableName
            GROUP   BY foreign_ID
        ) b ON  a.foreign_ID = b.foreign_ID AND
                a.ID = b.max_ID

输出

╔════╦════════════╦═══════╗
║ ID ║ FOREIGN_ID ║ VALUE ║
╠════╬════════════╬═══════╣
║  3 ║          1 ║ y     ║
║  4 ║          2 ║ x     ║
║  5 ║          3 ║ x     ║
╚════╩════════════╩═══════╝
于 2013-03-14T09:20:27.677 回答
0
`SELECT MAX(id) AS ID, 
       foreign_id,
       value 
 FROM tbl
 GROUP BY  foreign_id ASC`

对于少量结果,此答案非常好,但如果您使用大量数据,则可能仅“值”字段的值错误。另一种方法更适合您获得适当的价值,这里是这段代码。

`SELECT MAX(id) AS ID, 
       foreign_id,
       value 
 FROM tbl
 WHERE id in ( SELECT MAX(id) FROM tbl )
 GROUP BY  foreign_id ASC`
于 2013-03-14T09:28:28.023 回答