SELECT 一些不同的列
SELECT some distinct columns
这是一些测试数据。
+----+------+-------+---------+---------+
| 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 |
+----+------+-------+---------+---------+
我想要 SELECT 最新的行,其中 "type" 和 "account" 是唯一的。
例如,对于那个测试 table,我想要结果:
+----+------+-------+---------+---------+
| 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 |
+----+------+-------+---------+---------+
执行此操作的正确方法是什么?
如果您的查询为您提供了正确的 ID,您应该尝试将其放入子查询中:
SELECT * FROM test WHERE id IN (SELECT id FROM test GROUP BY type, account)
假设"latest row"表示最大的id
,那么有几种方法。使用in
的方法是:
SELECT t.*
FROM test t
WHERE t.id IN (SELECT MAX(id) FROM test t2 GROUP BY type, account)
这是一些测试数据。
+----+------+-------+---------+---------+
| 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 |
+----+------+-------+---------+---------+
我想要 SELECT 最新的行,其中 "type" 和 "account" 是唯一的。
例如,对于那个测试 table,我想要结果:
+----+------+-------+---------+---------+
| 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 |
+----+------+-------+---------+---------+
执行此操作的正确方法是什么?
如果您的查询为您提供了正确的 ID,您应该尝试将其放入子查询中:
SELECT * FROM test WHERE id IN (SELECT id FROM test GROUP BY type, account)
假设"latest row"表示最大的id
,那么有几种方法。使用in
的方法是:
SELECT t.*
FROM test t
WHERE t.id IN (SELECT MAX(id) FROM test t2 GROUP BY type, account)