如何使用sql子查询进行分组

Chr*_*abe 4 mysql sql

我现在想不清楚,我想通过station_id返回计数,输出的例子是:

station 1有3个fb帖子,6个linkedin帖子,5个邮件帖子站2个有3个fb帖子,6个linkedin帖子,5个邮件帖子

所以我需要按站ID分组,我的表结构是

CREATE TABLE IF NOT EXISTS `posts` (
  `post_id` bigint(11) NOT NULL auto_increment,
  `station_id` varchar(25) NOT NULL,
  `user_id` varchar(25) NOT NULL,
  `dated` datetime NOT NULL,
  `type` enum('fb','linkedin','email') NOT NULL,
  PRIMARY KEY  (`post_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=x ;
Run Code Online (Sandbox Code Playgroud)

到目前为止我的查询是返回0站,当它有一个时有2个帖子(db tho中有2个)

SELECT Station_id, (select count(*) FROM posts WHERE type = 'linkedin') AS linkedin_count, (select count(*) FROM posts WHERE type = 'fb') AS fb_count, (select count(*) FROM posts WHERE type = 'email') AS email_count  FROM `posts` GROUP BY station_id;
Run Code Online (Sandbox Code Playgroud)

Geo*_*rey 14

或者,以最快的方式,避免连接和子选择以您想要的确切格式获取它:

SELECT
  station_id,
  SUM(CASE WHEN type = 'linkedin' THEN 1 ELSE 0 END) AS 'linkedin',
  SUM(CASE WHEN type = 'fb'       THEN 1 ELSE 0 END) AS 'fb',
  SUM(CASE WHEN type = 'email'    THEN 1 ELSE 0 END) AS 'email'
FROM posts
GROUP BY station_id;
Run Code Online (Sandbox Code Playgroud)

输出:

+------------+----------+------+-------+
| station_id | linkedin | fb   | email |
+------------+----------+------+-------+
| 1          |        3 |    2 |     5 |
| 2          |        2 |    0 |     1 |
+------------+----------+------+-------+
Run Code Online (Sandbox Code Playgroud)

你可能还想在那里放一个索引来加速它

ALTER TABLE posts ADD INDEX (station_id, type);
Run Code Online (Sandbox Code Playgroud)

解释输出:

+----+-------------+-------+-------+---------------+------------+---------+------+------+-------------+
| id | select_type | table | type  | possible_keys | key        | key_len | ref  | rows | Extra       |
+----+-------------+-------+-------+---------------+------------+---------+------+------+-------------+
|  1 | SIMPLE      | posts | index | NULL          | station_id | 28      | NULL |   13 | Using index |
+----+-------------+-------+-------+---------------+------------+---------+------+------+-------------+
Run Code Online (Sandbox Code Playgroud)