Postgres - DISTINCT ON是否优先考虑列中的非空值?

use*_*536 2 sql postgresql

如果我DISTINCT ON在2列上使用,并且第三列可以具有空值,那么DISTINCT ON总是尝试返回第三列不为空的行,或者它是否只是向下ORDER BY

例如,使用此表:

col1    col2   col3
1       88     8
1       88     9
1       88     1
2       88     3 
2       88
3       88
Run Code Online (Sandbox Code Playgroud)

我希望能够SELECT DISTINCT ON (col1, col2)获得col3不为null的行,除非DISTINCT ON (col1, col2)没有行col3不为null.

Pau*_*rth 8

它完全基于你ORDER BY.如果您想要使用非行的行NULL col3,只需在您的订购中包含:

SELECT DISTINCT ON (col1, col2) ... ORDER BY col1, col2, col3 ASC NULLS LAST.