首页 > 解决方案 > 在子查询中使用 distinct on

问题描述

我注意到在 PostgreSQL 中,以下两个查询输出不同的结果:

select a.*
from (
    select distinct on (t1.col1)
        t1.*
    from t1
    order by t1.col1, t1.col2
) a
where a.col3 = value
;
create table temp as
select distinct on (t1.col1)
    t1.*
from t1
order by t1.col1, t1.col2
;
select temp.*
from temp
where temp.col3 = value
;

我想这与distinct on在子查询中使用有关。

在子查询中使用的正确方法是什么distinct on?例如,如果我不使用where语句,我可以使用它吗?或者在像这样的查询中

(
select distinct on (a.col1)
    a.*
from a
)
union
(
select distinct on (b.col1)
    b.*
from b
)

标签: sqlpostgresqlsql-order-bydistinctgreatest-n-per-group

解决方案


在正常情况下,两个示例应该返回相同的结果。

我怀疑您得到不同的结果,因为order by您的子查询的子句distinct on不是确定性的。也就是说,可能有几行t1共享同一个col1col2

如果 中的列order by不能唯一标识每一行,那么数据库必须自己决定哪一行将保留在结果集中:结果是结果不稳定,这意味着同一查询的连续执行可能产生不同的结果。

确保您的order by子句是确定性的(例如通过在子句中添加更多列),并且不再出现此问题。


推荐阅读