1

我现在正在写一个复杂的网站,我有点卡住了。我正在编写一个返回项目类别数据的查询。我需要它为每个类别返回一个数组,其中包括类别名称、id 和描述,以及使用该类别的项目数以及该类别下每个项目的值加起来。

换句话说,我想返回:

categoryid = 1
name = category name
description = category description
totalavailable = number of items in category
totaldownloads = downloads value from each item in category added together.

到目前为止,这是我的查询(它只返回计数和总和,它们并没有真正起作用)。

SELECT
  category, SUM(downloads) as totaldownloads, count(*) as totalavailable
FROM
  downloads
WHERE
   category IN(SELECT categoryid FROM categories)

这是我的架构的图片: 我的数据库架构

请帮我!我被困住了!

4

1 回答 1

0

你的查询几乎是完美的,你只需要JOIN两个表来获取所有值:

SELECT
  c.categoryid,
  c.name,
  c.description,
  COUNT(*) AS totalavailable,
  SUM(d.downloads) AS totaldownloads
FROM
  categories c
INNER JOIN
  downloads d
ON
  c.categoryid = d.category
WHERE
  /* whatever */
GROUP BY
  c.categoryid,
  c.name,
  c.description
于 2012-12-01T23:39:54.627 回答