1. 程式人生 > >mysql子查詢例子

mysql子查詢例子

-- 子表查詢
create table stus(
id int not null auto_increment ,
name varchar(10) ,
age tinyint ,
c_id int ,
height int ,
primary key (id)
);
insert into stus values(default,'xiaoming',23,1,175);
insert into stus values(default,'hongli',21,1,162);
insert into stus values(default,'susan',22,1,157);
insert into stus values(default,'aitao',25,3,178);
insert into stus values(default,'buli',26,2,172);
insert into stus values(default,'hongxue',28,3,177);
insert into stus values(default,'haolin',24,2,180);
insert into stus values(default,'qimiao',19,5,152);
insert into stus values(default,'huijuan',31,null,168);
create table classes(
id int auto_increment,
c_name varchar(15),
c_number int,
primary key(id)
);
insert into classes value(null,'php20141115',3013);
insert into classes value(null,'php20141215',3011);
insert into classes value(null,'php20141015',3010);
-- 查詢一個值 :已知班級名稱是'php20141115',要查詢這個班裡的學生
-- php邏輯
select id from classes where c_name = 'php20141115';
-- 再根據id在學生表裡查詢
select * from stus where c_id=id;
-- 子表查詢方法
select * from stus where c_id= (select id from classes where c_name = 'php20141115');
select * from stus where height = (select max(height) from stus);
select * from stus where age=(select max(age) from stus);


-- 查詢所有學生,並且是在已有的班級中
select * from stus where c_id is not null;
-- 上面結果不對
-- php邏輯:先查出所有班級id,根據id查詢學生
select id from classes;
select * from stus where c_id in (id);
-- mysql列子表查詢
select * from stus where c_id in (select id from classes);
select * from stus where c_id != all(select id from classes);


-- age,height 都是最高的學生
select * from stus where (age,height)= (select max(age),max(height) from stus);
-- 將年齡最大的學生高度改為182
update stus set height =182 where id= (select id from stus where age=31);
-- 上面語句報錯,可見子查詢只能用在查詢語句中。


-- order by 想要在group by 之前執行,from子查詢可以做到:學生按班級分組,查出每個班裡最高的學生
select * from stus group by c_id order by height desc;
select * from (select * from stus order by height desc) stus2 group by c_id ;