选择一些不同的列

时间:2015-05-10 20:48:57

标签: mysql select

这是一些测试数据。

+----+------+-------+---------+---------+
| 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 |
+----+------+-------+---------+---------+

我尝试过GROUP BY的变体:

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 |
+----+------+-------+---------+---------+

这样做的正确方法是什么?

2 个答案:

答案 0 :(得分:2)

假设&#34;最新的行&#34;表示具有最大id的那个,那么有几种方法。使用in的方法是:

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

答案 1 :(得分:-1)

如果您的查询为您提供了正确的ID,您应该尝试将其放入子查询中:

SELECT * FROM test WHERE id IN (SELECT id FROM test GROUP BY type, account)
相关问题