PostgreSQL - 选择 column1 where MIN(column2)

时间:2021-03-08 12:52:14

标签: sql postgresql postgresql-13

注意:我想避免因性能原因而区分。

注意 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     |

我想通过sort获取最低image_url行的t1_id列,类似于以下内容:

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     |

提前致谢!

1 个答案:

答案 0 :(得分:2)

Postgres 有一个方便的扩展名为 distinct on

select distinct on (t1_id) t2.*
from t2
order by t1_id, sort asc;

这通常是解决此类问题的最快方法。特别是,这可以利用 (t1_id, sort [desc]) 上的索引。

但是,您可以尝试另一种方法,例如:

select t2.*
from t2
where t2.sort = (select min(tt2.sort)
                 from t2 tt2
                 where tt2.t1_id = t2.t1_id
                );

这将使用相同的索引。如果这样更快,请发表评论并附上相关性能。