我做了两个我认为应该有相同结果的查询:
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 子句的位置在这种情况下会有所不同。谁能解释一下?或者有没有更好的方式来表达这个问题?