---
title: "mysql的多表查询"
author: "chenkaiadd"
date: "2012-10-23T18:46:45Z"
tags: []
categories: ["数据库"]
slug: "mysql"
draft: false
lastmod: "2012-10-23T18:46:45Z"
id: 1703971
url: "https://chenkaiadd.iteye.com/blog/1703971"
---

一道面试题

--tableA  class

--id 班级id

--class\_name  班级名称

 

--tableB  student

--id  学生id

--studnet\_name  学生名字

--class\_id  班级id

--gender  学生性别

--score   分数

 

create table t\_class(

  id int primary key auto\_increment,

  class\_name varchar(12) not null

);

 

create table t\_student(

 id int primary key auto\_increment,

 student\_name varchar(12) not null,

 class\_id  int not null,

 gender varchar(6) not null,

 score int not null

);

 

insert into t\_class(class\_name)

  values("classA"),

  ("classB"),

  ("classC");

 

insert into t\_student(student\_name,class\_id,gender,score) 

          values("kitty",1,"female",86),

                ("lucy",2,"male",96),

                ("momo",3,"female",46),

                ("Tom",1,"female",98),

                ("sch",2,"male",59),

                ("pitty",2,"female",61),

                ("lily",1,"female",76),

                ("stylr",2,"female",43),

                ("john",2,"male",78),

                ("vae",3,"female",68),

                ("jolin",2,"female",81),

                ("panpan",2,"female",49),

                ("looser",2,"male",89);

 

 

--问题1 找出某个班级女生多于3人的班级名称；

 

--问题2 把班级名称为 classA 班级的所有女生性别改为男生;

 

 

 

--问题3 求出班级名称为 classA 的人的平均分;

 

答案： select class\_name from t\_class where id=(select class\_id from t\_student where gender='female' group by class\_id having count(class\_id)=4 );

 

update t\_student set gender='male' where class\_id=(select id from t\_class where t\_class.class\_name='classA');

 

select avg(score) from t\_student studnt where class\_id=(select id from t\_class where t\_class.class\_name='classA');