我想计算每个用户相册的照片数量,直到用户在一个相册中没有照片,然后(我认为)WHERE ap.del = 0
该相册不会出现。请帮忙,DB是Postgresql!
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;
答案 0 :(得分:2)
如果你想在没有album_photo时显示它,你可以这样做:
WHERE ap.del = 0 OR ap.id_album IS NULL
如果没有album_photo,则LEFT JOIN将返回所有album_photo值为NULL。检查NULL的连接键将显示没有加入任何行。
答案 1 :(得分:1)
将WHERE ap.del = 0
移至JOIN
LEFT JOIN album_photo ap ON ap.id_album = a.id_album AND ap.del = 0
NULL
时, ap.del将为album_photo
,这意味着WHERE
子句将过滤掉ap.del为空的行。由于NULL = 0
未知并返回false。
同样的事情适用于您想要在LEFT/RIGHT JOIN
上过滤的任何时间。
答案 2 :(得分: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;