我试图创建一个基本上等于此的查询(不起作用)。
SELECT * FROM `categories` AS C AND
SELECT * FROM `items` AS I AND
SELECT COUNT(I.id) AS items AND
SELECT SUM(I.price) AS price;
我没有使用SQLServer,而且我通过PHP使用PDO进行数据库连接。
这是表格。
分类
+----+------------+ | id | Category | +----+------------+ | 1 | First_Cat | | 2 | Second_Cat | +----+------------+
项
+----+----------+------+-------+
| id | category | name | price |
+----+----------+------+-------+
| 1 | 1 | Foo | 1.99 |
| 2 | 1 | Bar | 2.00 |
| 3 | 2 | ooF | 0.99 |
| 4 | 2 | raB | 1.99 |
+----+----------+------+-------+
基于这些表格,我期待这些查询结果:
+----+------------+-------+-------+--+
| id | category | items | price | |
+----+------------+-------+-------+--+
| 1 | First_Cat | 2 | 3.99 | |
| 2 | Second_Cat | 2 | 2.98 | |
+----+------------+-------+-------+--+
有任何帮助吗?
答案 0 :(得分:2)
您在评论中发布的查询未加入类别表和项目表。这让我觉得你可以做这样的事情吗?:
SELECT
categories.id,
categories.Category,
COUNT(*) AS items,
SUM(items.price) as price
FROM
`categories`
JOIN items
ON categories.id = items.category
GROUP BY
categories.id,
categories.Category