我有一个名为“ posts ”的表,其中包含id、post、status等字段。我想创建一个查询来通过帖子的状态获取帖子计数,如下所示
------------------------------
| published | draft | trash |
------------------------------
| 150 | 15 | 0 |
------------------------------
请帮我 :
SELECT status, COUNT(*) count FROM posts GROUP BY status
这是更典型的,会给你以下。
-----------------------
| status | count |
-----------------------
| published | 150 |
-----------------------
| draft | 15 |
-----------------------
| trash | 0 |
-----------------------
如果你想要你要求的桌子,做
SELECT SUM(CASE status WHEN 'published' THEN 1 ELSE 0 END) published,
SUM(CASE status WHEN 'draft' THEN 1 ELSE 0 END) draft,
SUM(CASE status WHEN 'trash' THEN 1 ELSE 0 END) trash
FROM posts
SELECT status, COUNT(*)
FROM posts
GROUP BY status
SELECT published , COUNT(*) FROM posts WHERE
发表= 150;
或者
SELECT published , COUNT(*) FROM posts;
完美的解决方案,如您所见:
**
SELECT SUM(main_a.published) as published, SUM(main_a.draft) as draft, SUM(main_a.trash) as trash FROM (SELECT
IF (`status`= 'published' ,COUNT(*), 0 ) AS published,
IF (`status`= 'draft' , COUNT(*) , 0) AS draft,
IF (`status`= 'trash', COUNT(*) , 0) AS trash FROM posts GROUP BY `status` ) main_a
**
请注意您的表结构应如下所示:
CREATE TABLE `posts` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`post` text,
`status` enum('published','draft','trash') DEFAULT NULL,
PRIMARY KEY (`id`)
)
SELECT SUM(main_a.published) as published, SUM(main_a.draft) as draft, SUM(main_a.trash) as trash FROM (SELECT IF (status= 'published' ,COUNT(), 0 ) AS published, IF (status= 'draft' , COUNT() , 0) AS draft, IF (status= 'trash', COUNT(*) , 0) AS trash FROM posts GROUP BY status ) main_a