2013-03-14 46 views

回答

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 

FIDDLE

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  ║ 
╚════╩════════════╩═══════╝ 
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與實際的表名。

0
`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` 
相關問題