类别
| id | tID | category |
-----------------------
| 1 | 1 | Foo |
| 2 | 1 | Bar |
| 3 | 2 | Fox |
| 4 | 3 | Box |
| 5 | 2 | Chair |
上传
| id | category | data | act
| 1 | 1 | some | 1
| 2 | 1 | thin | 0
| 3 | 3 | fat | 0
| 4 | 2 | key | 0
| 5 | 1 | lad | 1
从类别中选择类别,并计算从上传中具有相同类别ID的总上传ID,其中act等于1。
结果
|category| count|
| 1 | 2 |
| 2 | 0 |
| 3 | 0 |
| 4 | 0 |
| 5 | 1 |
到目前为止我的尝试。
SELECT COUNT(u.category), c.category FROM categories c LEFT JOIN upload u ON c.id = u.category GROUP BY u.category
查询应该是什么?
答案 0 :(得分:0)
正确的答案可能是以下几行。如果这不对,那么你需要更仔细地考虑你的标准......
DROP TABLE IF EXISTS categories;
CREATE TABLE categories
(id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
,tID INT NOT NULL
,category VARCHAR(12) NOT NULL
);
INSERT INTO categories VALUES
(1,1,'Foo'),
(2,1,'Bar'),
(3,2,'Fox'),
(4,3,'Box'),
(5,2,'Chair');
DROP TABLE IF EXISTS upload;
CREATE TABLE upload
(id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
,category INT NOT NULL
,data VARCHAR(12) NOT NULL
,act TINYINT NOT NULL
);
INSERT INTO upload VALUES
(1,1,'some',1),
(2,1,'thin',0),
(3,3,'fat',0),
(4,2,'key',0),
(5,1,'lad',1);
SELECT c.category
, COALESCE(SUM(u.act = 1),0) ttl
FROM categories c
LEFT
JOIN upload u
ON u.category = c.id
GROUP
BY c.category;
+----------+------+
| category | ttl |
+----------+------+
| Bar | 0 |
| Box | 0 |
| Chair | 0 |
| Foo | 2 |
| Fox | 0 |
+----------+------+