计算一个表中具有2级子项的总行数

时间:2012-11-06 19:08:52

标签: mysql sql

我有一个“画廊”表和一个“图像”表......画廊表就像这样..

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)

这样做的最佳方法是什么,我不想把查询放在循环中它会把负载放在服务器上,请指教..

感谢

2 个答案:

答案 0 :(得分:3)

COUNT使用GROUP 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 Fiddle Demo

答案 1 :(得分:2)

这是按图片库name分组的基本aggregate COUNT()

重要的是,必须使用 LEFT 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