考慮以下4個表:左外連接兩層深在的Postgres導致笛卡爾積
CREATE TABLE events (id, name)
CREATE TABLE profiles (id, event_id)
CREATE TABLE donations (amount, profile_id)
CREATE TABLE event_members(id, event_id, user_id)
我試圖獲取所有事件的列表,任何成員的計數一起,和任何捐款的總和。問題是捐贈總額回來錯誤(似乎是慷慨的捐贈活動*#event_members)。
這裏是SQL查詢(Postgres的)
SELECT events.name, COUNT(DISTINCT event_members.id), SUM(donations.amount)
FROM events
LEFT OUTER JOIN profiles ON events.id = profiles.event_id
LEFT OUTER JOIN donations ON donations.profile_id = profiles.id
LEFT OUTER JOIN event_members ON event_members.event_id = events.id
GROUP BY events.name
的總和(donations.amount)就要回來=以捐款的實際總和*在event_members的行數。如果我註釋掉count(不同的event_members.id)和event_members離開外部連接,那麼總和是正確的。
編輯:歐文指出我在正確的方向。查詢改寫爲:
SELECT events.name, COUNT(DISTINCT event_members.id), select(SUM(donations.amount) from donations,profiles where donations.profile_id = profiles.id and profiles.event_id = events.id) as total_donations FROM events LEFT OUTER JOIN event_members ON event_members.event_id = events.id GROUP BY events.name
順便說一句,改變總和(donations.amount)爲count(distinct donations.id)確實會導致正確的捐贈數量 –
嗨,只需重新排序您的問題中的create table語句以反映join參數。 – biziclop
密切相關:http://stackoverflow.com/questions/12464037/two-sql-left-joins-produce-incorrect-result –