2015-05-10 66 views
0

這是一些測試數據。選擇一些不同的列

+----+------+-------+---------+---------+ 
| id | type | param | enabled | account | 
+----+------+-------+---------+---------+ 
| 1 | test |  a |  1 | null | 
| 2 | asdf |  b |  1 | null | 
| 3 | test |  c |  1 |  34 | 
| 4 | test |  d |  0 |  34 | 
| 5 | asdf |  e |  1 | null | 
+----+------+-------+---------+---------+ 

我想選擇最新的行,其中「類型」和「帳戶」是唯一的。

例如,對於測試表,我想要的結果:

+----+------+-------+---------+---------+ 
| id | type | param | enabled | account | 
+----+------+-------+---------+---------+ 
| 1 | test |  a |  1 | null | 
| 4 | test |  d |  0 |  34 | 
| 5 | asdf |  e |  1 | null | 
+----+------+-------+---------+---------+ 

我試着按組的變化:

SELECT * FROM test GROUP BY type, account 

出於某種原因,讓我這樣的:

+----+------+-------+---------+---------+ 
| id | type | param | enabled | account | 
+----+------+-------+---------+---------+ 
| 1 | test |  a |  1 | null | 
| 4 | test |  d |  1 |  34 | <- note that enabled is taking on an incorrect value. 
| 5 | asdf |  e |  1 | null | 
+----+------+-------+---------+---------+ 

什麼是正確的方法來做到這一點?

+0

您試過'SELECT DISTINCT * FROM test'嗎? –

+1

DISTINCT適用於所有選定的列。所以在這個例子中,它會選擇'id','type','param','enabled'和'account'都是唯一的。我只想'類型'和'帳戶'是唯一的。 – ieatpizza

回答

-1

如果您的查詢是給你正確的ID,你應該嘗試把它變成一個子查詢:

SELECT * FROM test WHERE id IN (SELECT id FROM test GROUP BY type, account) 
+0

這有效。謝謝! – ieatpizza

+0

這不適合我。返回所有行。見下面的解決方案 – DCR

2

假設「最新行」是指具有最大id,那麼有幾種方法。使用in的方法是:

SELECT t.* 
FROM test t 
WHERE t.id IN (SELECT MAX(id) FROM test t2 GROUP BY type, account)