postgresql where子句的行为

时间:2012-11-26 06:49:19

标签: postgresql

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

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';

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

1 个答案:

答案 0 :(得分: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;

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