select * from 表名; *代表所有列,效率低;
select id,sname,age,sex from 表名;
2.条件查询:
查询所有的男生;
select * from student where sex='男';
查询已经成年的学生
select * from student where age >= 18;
查询姓名不为null的同学;
select * from student where sname is not null;
查询id是1,3,5,7,9的学生
select * from student where id in(1,3,5,7,9);
3.聚合查询:
查询最大的学生:
max(age):select max(age) from student;
查询最小的学生:
min(age):select min(age) from student;
平静年龄:
avg(age):select avg(age) from student;
总条数:
count(*):select count(*) from student;
有几个男生:
select count(*) from student where sex='男';
年龄总和:
sum(age):select sum(age) from student;
4.别名:as关键字可以省略不写
select sname as '姓名' from t_stu;
5.排序:null最为最小值存在的;
order by 默认是升序:asc
降序是desc;-->desc是关键字,不能作为列名,表名称存在;
根据id升序排序:
select * from t_stu order by id;
6.分组:group by;
性别分组:两组 男:10 女:10
select sex,count(*) from t_stu group by sex;
根据商品的类型分组:
select gtype,count(*) from goods group by gtype;
7.模糊查询:
like : _代表一个字符 %代表多个字符
查询名字有两个字符构成的学生:
select * from t_stu where sname like '__';
查询名字中包含三的学生:
select * from t_stu where sname like '%三%'
查询姓张的学生;
select * from t_stu where same like '张%'
级联操作:
create table student(sid int(10)primary key auto_increment,sname varchar(20),cid int(10),
foreign key(cid) references class(cid) on delete cascade on update cascade
);
关联查询:
笛卡尔集:
select * from student,class;--->两张表的条数相乘
where等值联查:92语法 习惯使用92语法
select * from student s,class c where s.cid = c.cid;
inner join on:内连接查询:99语法 建议使用
select * from student s inner join class c on s.cid = c.cid;
特点:
只展示符合条件的数据