比方說,我們有這個表名爲表一MySQL - 如何獲取按特定字段分組的最新行值?
id foreign_id value
1 1 x
2 2 y
3 1 y
4 2 x
5 3 x
其中id
是主鍵
你如何獲得最新的行(我們將在id
的以立足本)分組由外國身份證?基本上,我想是
id foreign_id value
3 1 y
4 2 x
5 3 x
比方說,我們有這個表名爲表一MySQL - 如何獲取按特定字段分組的最新行值?
id foreign_id value
1 1 x
2 2 y
3 1 y
4 2 x
5 3 x
其中id
是主鍵
你如何獲得最新的行(我們將在id
的以立足本)分組由外國身份證?基本上,我想是
id foreign_id value
3 1 y
4 2 x
5 3 x
嘗試此查詢
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
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 ║
╚════╩════════════╩═══════╝
嘗試此查詢,
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
與實際的表名。
`SELECT MAX(id) AS ID,
foreign_id,
value
FROM tbl
GROUP BY foreign_id ASC`
這個ans對於少量的結果來說相當好,但是如果你使用大量的數據,那麼它可能只對「value」字段有錯誤的值。另一種方法更適合你獲得適當的價值,這裏是這個代碼。
`SELECT MAX(id) AS ID,
foreign_id,
value
FROM tbl
WHERE id in (SELECT MAX(id) FROM tbl)
GROUP BY foreign_id ASC`