Mysql多表操作

多表查询

一、普通多表查询
class表
create table class(
in int unsigned auto_increment,
name varchar(30) not null
primary key(id));

user表
create table user(
id int unsigned auto_increment,
username varchar(30) not null,
password varchar(30) not null,
class_id int not null,
primary key(id));

01)、多表查询
a、打印出每个学员的姓名和班级
select user.username,class.name from user,class where user.class_id = class.id;
02)、表与表关系:
1、有关系
#表与表发生关系,对应字段属性要一一相同
2、没关系


有关系:
1、合并
2、分离
#一个表一个主体
#两个表是一对一关系,则可以合并


表与表有哪些关系:
1、一对一
2、一对多
3、多对多


二、嵌套查询(一般用于自身查询)
select * from user where id in(select max(id) from user);
三、链接查询
需求:把所有班的总人数统计出来,前提是有些班没有人
select class.name,count(user.id) from class left join user on class.id=user.class_id group by class.id;
|name             | count(user.id)      |
|class one            | 2|
|class two            |                      3|
|class three          | 3|
|class four     | 0|


需求:把所有班的总人数统计出来,前提是有些班没有人?注:人数为0的则打印出“无”
select class.name,if(count(user.id),count(user.id),'无') from class left join user on class.id=user.class_id group by class.id;
|name         |count(user.id)           |
|class one        | 2|
|class two        |                          3|
|class three      | 3|
|class four |        无|


左链接:左边的表数据全部输出
右链接:右边的表数据全部输出
select class.name ,count(user.id) from user right join class on user.class_id=class.id group by class.id;
内连接:完全等于普通多表查询,必须是符合条件的多个表的数据才会显示
select class.name,count(user.id) from user inner join class on user.class_id=class.id group by class.id;
select class.name,count(user.id) from user where user.class_id=class.id group by class.id;

需求:用户表有很多用户,有一列是成绩,请统计这张表中及格人数和不及格人数(请用一条sql语句)

1、创建表
creata table user(
id int unsigned not null auto_increment,
username varchar(50) not null,
score int not null,
primary key(id));

insert into user(username,score) values('user1',98);
...
insert into user(username,score) values('user10',67);

2、答案一
select (select count(*) from user where score>=60) yes,(select count(*) from user1 where score<60) no;
   答案二
        select sum(if(score>=60,1,0)) 及格,sum(if(score<60,1,0)) 不及格 from user;
发布了55 篇原创文章 · 获赞 2 · 访问量 2万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章