0

我有一个名为“ posts ”的表,其中包含id、post、status等字段。我想创建一个查询来通过帖子的状态获取帖子计数,如下所示

------------------------------
| published | draft  | trash | 
------------------------------
| 150       |  15    |  0    |
------------------------------

请帮我 :

4

5 回答 5

1
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 
于 2013-10-28T06:14:56.587 回答
1
SELECT   status, COUNT(*)
FROM     posts
GROUP BY status
于 2013-10-28T06:16:42.250 回答
1

SELECT published , COUNT(*) FROM posts WHERE发表= 150;

或者

SELECT published , COUNT(*) FROM posts;

于 2013-10-28T06:17:15.627 回答
0

完美的解决方案,如您所见:

**

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`)
) 
于 2013-10-28T06:40:22.733 回答
0
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
于 2013-10-28T06:45:11.663 回答