1

我有一张“画廊”表和一张“图片”表。画廊表是这样的。

gal_id|name

和图像就像

img_id|gal_id|name

现在我说 20 个画廊,我想显示每个画廊中的图像总数,所以我想使用一个查询来返回每个画廊中包含总图像的数组,如下所示

Gallery A (Total Images : 23)
Gallery B (Total Images : 33)
Gallery C (Total Images : 523)
Gallery D (Total Images : 25)

执行此操作的最佳方法是什么,我不想将查询置于循环中,它将负载加载到服务器上,请告知..

谢谢

4

2 回答 2

3

COUNTGROUP BY这样使用:

SELECT g.name 'Gallery Name', COUNT(i.img_id) 'Total Images'
FROM galleries g
INNER JOIN images i ON g.gal_id = i.gal_id
GROUP BY g.name

SQL 小提琴演示

于 2012-11-06T19:10:56.907 回答
2

这是按画廊分组的基本聚合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
于 2012-11-06T19:11:38.370 回答