子查询作为列:嵌套子查询

时间:2016-08-12 19:08:28

标签: mysql

我有两张桌子'学生'和'团队'。我想根据团队名称显示学生人数,团队中的Team_id是主键。

我试过这个

(SELECT(SELECT team,count(*) as team 
            FROM student GROUP BY team) AS total,
     (SELECT team_name 
          from team WHERE team_id IN (SELECT team 
              FROM student GROUP BY team)) as team)

我希望输出为

Team Name      Total Student
-----------------------------
Team 1           25
Team 2           10

表'学生'

CREATE TABLE IF NOT EXISTS `student` (
  `id` int(255) NOT NULL AUTO_INCREMENT,
  `rid` varchar(200) NOT NULL,
  `sid` varchar(200) NOT NULL,
  `name` varchar(600) NOT NULL,
  `age` varchar(200) NOT NULL,
  `dob` varchar(200) NOT NULL,
  `sex` varchar(200) NOT NULL,
  `weight` varchar(200) NOT NULL,
  `height` varchar(200) NOT NULL,
  `team` varchar(600) NOT NULL,
  `age_group` varchar(200) NOT NULL,
  `weight_group` varchar(500) NOT NULL,
  `belt` varchar(200) NOT NULL,
  `black_belt` varchar(200) NOT NULL,
  `ikata` varchar(20) NOT NULL,
  `ikumite` varchar(20) NOT NULL,
  `team_kata` varchar(20) NOT NULL,
  `special_entry` varchar(20) NOT NULL,
  `challange` varchar(50) NOT NULL,
  `state` varchar(200) NOT NULL,
  `weapon` varchar(200) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=6 DEFAULT CHARSET=latin1;

表'团队'

CREATE TABLE IF NOT EXISTS `team` (
  `id` int(20) NOT NULL AUTO_INCREMENT,
  `team_id` varchar(500) NOT NULL,
  `team_name` varchar(500) NOT NULL,
  `address` varchar(500) NOT NULL,
  `coach_name` varchar(500) NOT NULL,
  `coach_number` varchar(500) NOT NULL,
  `coach_email` varchar(500) NOT NULL,
  `gold` varchar(200) NOT NULL,
  `state` varchar(500) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=latin1;

1 个答案:

答案 0 :(得分:1)

好像你在找这个

 select a.team_name, count(*) 
 from  team as a
 inner join student as b on a.id = b.team
 group by a.team_name

(使用适当的列进行加入)