PostgreSQL — Select column1 其中 MIN(column2)
PostgreSQL — Select column1 where MIN(column2)
注意:出于性能原因,我想避免区分。
注意 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 |
提前致谢!
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
);
这将使用相同的索引。如果这样更快,请post评论相关性能。
注意:出于性能原因,我想避免区分。
注意 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 |
提前致谢!
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
);
这将使用相同的索引。如果这样更快,请post评论相关性能。