这是按画廊分组的基本聚合COUNT()
name
。
重要的是,这必须使用 aLEFT JOIN
来确保没有图像的画廊返回零计数,而不是根本不返回任何行。
SELECT
galleries.name,
COUNT(images.img_id) AS total_images
FROM
galleries
/* LEFT JOIN will ensure empty galleries are listed */
LEFT JOIN images ON galleries.gal_id = images.gal_id
GROUP BY galleries.name
/* Sort by descending total_images */
ORDER BY total_images DESC
评论后更新
SELECT
galleries.name,
COUNT(images.img_id) AS total_images,
/* Differentiate between downloadable/not downloadable with a SUM(CASE) */
/* It converts each into a zero or one and then sums up the values */
SUM(CASE WHEN downloadable = 'Y' THEN 1 ELSE 0 END) AS downloadable,
SUM(CASE WHEN downloadable = 'N' THEN 1 ELSE 0 END) AS not_downloadable
FROM
galleries
/* LEFT JOIN will ensure empty galleries are listed */
LEFT JOIN images ON galleries.gal_id = images.gal_id
GROUP BY galleries.name
/* Sort by descending total_images */
ORDER BY total_images DESC