让我们假设给定的MYSQL表结构
+----+-------+-------+
| id | group | count |
+----+-------+-------+
| 1 | cat | 11 |
| 2 | cat | 12 |
| 3 | dog | 4 |
| 4 | dog | 6 |
| 5 | cow | 16 |
| 6 | cow | 12 |
+----+-------+-------+
我想要做的是:每个动物组取一只动物,按计数字段递增排序。在上面的示例中,输出应为:
| 1 | cat | 11 |
| 3 | dog | 4 |
| 6 | cow | 12 |
但它比看起来更复杂。获得结果的最优化查询是什么? (当然,为每个组制作子查询不是一种选择)
答案 0 :(得分:2)
根据手册......
import datetime, time
t = time.strptime("1:00", "%H:%M")
dt = datetime.datetime(*t[:6])
答案 1 :(得分:0)
从MySQL 8.0+
开始,您可以使用ROW_NUMBER()
:
SELECT *
FROM (SELECT *, ROW_NUMBER() OVER(PARTITION BY `group` ORDER BY `count`) AS rn
FROM table_name) sub
WHERE rn = 1;
<强> DBFiddle Demo 强>