4

我试图在 Postgres 中提交一个只返回不同元组的查询。在我的示例查询中,我不希望一个cluster_id/feed_id 组合存在多次的重复条目。如果我做一个简单的:

select distinct on (cluster_info.cluster_id, feed_id) 
   cluster_info.cluster_id, num_docs, feed_id, url_time 
   from url_info 
   join cluster_info on (cluster_info.cluster_id = url_info.cluster_id) 
   where feed_id in (select pot_seeder from potentials) 
   and num_docs > 5 and url_time > '2012-04-16';

我明白了,但我也想根据num_docs. 因此,当我执行以下操作时:

select distinct on (cluster_info.cluster_id, feed_id) 
   cluster_info.cluster_id, num_docs, feed_id, url_time 
   from url_info join cluster_info 
   on (cluster_info.cluster_id = url_info.cluster_id) 
   where feed_id in (select pot_seeder from potentials) 
   and num_docs > 5 and url_time > '2012-04-16' 
   order by num_docs desc;

我收到以下错误:

ERROR:  SELECT DISTINCT ON expressions must match initial ORDER BY expressions
LINE 1: select distinct on (cluster_info.cluster_id, feed_id) cluste...

我想我明白为什么我会收到错误(除非我以某种方式明确描述该组,否则不能按元组分组)但是我该怎么做呢?或者,如果我对错误的解释不正确,有没有办法实现我的初始目标?

4

1 回答 1

11

最左边的ORDER BY项目不能与DISTINCT从句的项目不一致。我引用手册关于DISTINCT

DISTINCT ON表达式必须匹配最左边的表达式ORDER BY 。ORDER BY 子句通常包含附加表达式,用于确定每个DISTINCT ON组中所需的行优先级。

尝试:

SELECT *
FROM  (
    SELECT DISTINCT ON (c.cluster_id, feed_id) 
           c.cluster_id, num_docs, feed_id, url_time 
    FROM   url_info u
    JOIN   cluster_info c ON (c.cluster_id = u.cluster_id) 
    WHERE  feed_id IN (SELECT pot_seeder FROM potentials) 
    AND    num_docs > 5
    AND    url_time > '2012-04-16'
    ORDER  BY c.cluster_id, feed_id, num_docs, url_time
           -- first columns match DISTINCT
           -- the rest to pick certain values for dupes
           -- or did you want to pick random values for dupes?
    ) x
ORDER  BY num_docs DESC;

或使用GROUP BY

SELECT c.cluster_id
     , num_docs
     , feed_id
     , url_time 
FROM   url_info u
JOIN   cluster_info c ON (c.cluster_id = u.cluster_id) 
WHERE  feed_id IN (SELECT pot_seeder FROM potentials) 
AND    num_docs > 5
AND    url_time > '2012-04-16'
GROUP  BY c.cluster_id, feed_id 
ORDER  BY num_docs DESC;

如果c.cluster_id, feed_id 是您在列表中包含列的所有(在这种情况下都是)表的主键列SELECT,那么这仅适用于 PostgreSQL 9.1或更高版本。

否则,您需要对GROUP BY其余列进行汇总或提供更多信息。

于 2012-04-21T18:42:02.160 回答