2011-03-31 186 views
0

我想爲每個用戶相冊統計照片數量,一切順利,直到用戶沒有在一個相冊中的照片,然後(我認爲)WHERE ap.del = 0做那個相冊沒有出現。請幫助,DB是Postgresql!SQL連接問題

SELECT a.id_album, a.id_osoba, a.name, a.description, a.privacy, a.del, a.data_del, a.cover, a.date, count(ap.id_album_photo) AS ilosc 
    FROM album a 
    LEFT JOIN album_photo ap ON ap.id_album = a.id_album 
    WHERE ap.del = 0 
    GROUP BY a.id_album, a.id_osoba, a.name, a.description, a.privacy, a.del, a.data_del, a.cover, a.date 
    ORDER BY a.name; 

回答

2

如果你想讓它顯示出來的時候沒有album_photo不管,你可以這樣做:

WHERE ap.del = 0 OR ap.id_album IS NULL 

如果沒有album_photo,在LEFT JOIN將只返回所有album_photo值NULL 。檢查對NULL的連接鍵會顯示該行沒有在加入。

1

移動WHERE ap.del = 0JOIN

LEFT JOIN album_photo ap ON ap.id_album = a.id_album AND ap.del = 0

ap.del將NULL當沒有album_photo,這意味着WHERE子句將過濾掉ap.del爲空的行。由於NULL = 0未知並返回false。

同樣的事情適用於任何時候您想過濾LEFT/RIGHT JOIN

1

如何:

SELECT 
    a.id_album, 
    a.id_osoba, 
    a.name, 
    a.description, 
    a.privacy, 
    a.del, 
    a.data_del, 
    a.cover, 
    a.date, 
    SUM(CASE 
     WHEN ap.id_album_photo IS NOT NULL THEN 1 
     ELSE 0 
    END) AS liczba 
FROM 
    album AS a 
LEFT JOIN 
    album_photo AS ap 
ON 
    a.id_album = ap.id_album 
AND 
    ap.del = 0 
GROUP BY 
    a.id_album, 
    a.id_osoba, 
    a.name, 
    a.description, 
    a.privacy, 
    a.del, 
    a.data_del, 
    a.cover, 
    a.date 
ORDER BY 
    a.name; 

SELECT 
    a.id_album, 
    a.id_osoba, 
    a.name, 
    a.description, 
    a.privacy, 
    a.del, 
    a.data_del, 
    a.cover, 
    a.date, 
    COALESCE(ap.liczba, 0) AS liczba 
FROM 
    album AS a 
LEFT JOIN 
    (
     SELECT 
      ap.id_album, 
      COUNT(1) AS liczba 
     FROM 
      album_photo AS ap 
     WHERE 
      ap.del = 0 
     GROUP BY 
      ap.id_album 
    ) AS ap 
ON 
    ap.id_album = a.id_album 
ORDER BY 
    a.name;