0

我做了两个我认为应该有相同结果的查询:

SELECT COUNT(*) FROM (
    SELECT DISTINCT ON (id1) id1, value 
    FROM (
        SELECT table1.id1, table2.value 
            FROM table1 
            JOIN table2 ON table1.id1=table2.id 
            WHERE table2.value = '1') 
    AS result1 ORDER BY id1) 
AS result2;

SELECT COUNT(*) FROM (
    SELECT DISTINCT ON (id1) id1, value 
    FROM (
        SELECT table1.id1, table2.value 
        FROM table1 
        JOIN table2 ON table1.id1=table2.id 
    ) 
    AS result1 ORDER BY id1) 
AS result2
WHERE value = '1';

唯一的区别是一个 WHERE 子句在 SELECT DISTINCT ON 内,另一个在 SELECT DISTINCT ON 之外,但在 SELECT COUNT 内。但结果并不相同。我不明白为什么 WHERE 子句的位置在这种情况下会有所不同。谁能解释一下?或者有没有更好的方式来表达这个问题?

4

1 回答 1

0

这是一个很好的方法来看待这个:

SELECT DISTINCT ON (id) id, value
  FROM (select 1 as id, 1 as value
        union
        select 1 as id, 2 as value) a;

SELECT DISTINCT ON (id) id, value
  FROM (select 1 as id, 1 as value
        union
        select 1 as id, 2 as value) a
 WHERE value = 2;

问题与独特的条件和可见的地方有关。这是设计的行为。

于 2013-04-14T08:15:44.050 回答