我正在写一个复杂的网站,我有点卡住了。我正在编写一个返回项目类别数据的查询。我需要它为每个类别返回一个数组,其中包括类别名称,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)
这是我的架构的图片:
请帮帮我!我被卡住了!
答案 0 :(得分: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