【发布时间】:2021-06-06 08:33:53
【问题描述】:
注意:出于性能原因,我想避免 DISTINCT ON。
注意 2:我错了。感谢@Gordon Linoff,使用正确的索引查询非常有效!
具有以下结构:
| id | image_url | sort | t1_id |
|----|---------------|------|-------|
| 1 | https://.../1 | 10 | 1 |
| 2 | https://.../2 | 20 | 1 |
| 3 | https://.../3 | 30 | 1 |
| 4 | https://.../4 | 30 | 2 |
| 5 | https://.../5 | 20 | 2 |
| 6 | https://.../6 | 10 | 2 |
我想通过t1_id获取最低sort行的image_url列,类似如下:
SELECT * FROM t2 WHERE MIN(sort) GROUP BY (t1_id);
得到以下结果:
| id | image_url | sort | t1_id |
|----|---------------|------|-------|
| 1 | https://.../1 | 10 | 1 |
| 6 | https://.../6 | 10 | 2 |
提前致谢!
【问题讨论】:
-
我很确定
DISTINCT ON不会比任何其他技术慢(例如使用ROW_NUMBER或 sbquery)。因此,您的问题更为普遍,您可能只想为您的 DBMS 提供适当的索引。
标签: sql postgresql postgresql-13