글

라벨이 PostgreSQL인 게시물 표시

PostgreSQL LEFT JOIN Drops Unmatched Rows When You Filter in WHERE

Move a right-table filter such as o.status = 'paid' into the ON clause when every left-side customer must remain. The WHERE clause evaluates the rows after the join and a right-hand comparison on the placeholder NULL does not pass. Verify the audience of the report In a synthetic dataset, Ava has one unpaid order, Bo has one paid order and Cai has no orders. The business rule says every customer appears. A WHERE predicate on order status would retain only Bo. Even adding OR o.id IS NULL would still lose Ava, because the initial join matched her unpaid order. Filter qualifying matches in the join SELECT c.id, COUNT(o.id) AS paid_orders FROM customers AS c LEFT JOIN orders AS o ON o.customer_id = c.id AND o.status = 'paid' GROUP BY c.id ORDER BY c.id; Assume orders.id is a non-null primary key. COUNT of that column skips the NULL placeholder, giving paid order counts of 0, 1 and 0. COUNT(*) would also count the placeholder row. Test each kind of customer Put...