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萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章