1、插入数据
insert into t_user (username,password,nickname) values ('foye','123','佛爷');
以下方式必须写出所有的字段
insert into t_user values (null,'eryuehong','456','二月红');
可以通过 insert into xxx select xxx 插入已有表中的数据
insert into t_user(username,nickname) select no,name from t_student;
2、简单查询
select * from 表名
查询条件
select * from 表名 where 条件
select * from t_user;
select id,username from t_user;
select * from t_user where id>2;
select * from t_user where id>2 and nickname='二月红';
3、更新
update 表名 set 字段名=新的值 where 条件
update t_user set username='baye',nickname='八爷' where id=2;
4、删除
delete from 表名 where 条件
delete from t_user where id=1;
使用truncate可以清空表中的全部信息,而且可以将自动递增的标识清空
truncate table t_student;
5、常用查询
like表示模糊查询:like '张%' 模糊查询张xx的数据
select * from t_stu where name like '李%'; (查询姓名为李xx的学生)
in表示某个值在某个数据中
select * from t_stu where cla_id in (1,2); (查询在1和2班级中的学生)
between可以查询某个范围内的数据
select * from t_stu where born between '1988-01-01' and '1989-12-30';
(查询出生日期在1988-01-01日至1989-12-30日的学生)
可以通过一些函数进行查询
select name as '姓名',year(now())-year(born) as '年龄' from t_stu where name like '李%';
(查询姓李的学生的姓名和年龄,as表示可以为投影取一个别名)
子查询
select * from t_stu where born=(select min(born) from t_stu where cla_id=3 and sex='男');
(查询班级在3班的年龄最大的男生,注意最好将查询条件放在子查询里)
查询为空的值应该使用 is null 而不是用 =null。
max()表示获取最大值。
min()表示获取最小值。
count()表示统计数量。
排序
select * from t_stu where cla_id=3 order by born desc;
(通过出生日期的降序排序)
select * from t_stu where cla_id=3 order by born;
(默认情况是通过升序排序,order by bord asc)
分组查询(分组查询主要用来统计相应的不同组别的信息)
select cla_id,count(id) from t_stu group by cla_id;
(以上可以分组获取每个班级中的学生总数)
select cla_id,count(id),max(born),min(born) from t_stu where cla_id is not null group by cla_id;
(通过班级进行分组,查询每个班级中年龄最大的值和年龄最小的值和班级的人数)
(分组查询中一样是可以加入查询条件的)
select cla_id,count(id) as pn,max(born),min(born) from t_stu where cla_id is not null group by cla_id having pn>60;
(当比较的条件是在查询出来的投影中时,不能使用where进行比较,而应该使用having进行比较,特别在group by经常使用)
6、跨表查询(连接查询)
1、相对较早的方式
select * from t_cla t1,t_stu t2 where t1.id = t2.cla_id and t1.id in (1,2,3);
较早的方式是通过where来连接几个主键和外键的。
2、目前常用的方式
常用的方式是使用join和on来连接的,join表示将表连接起来,on(连接的字段关系)
select t1.name,t2.name from t_cla t1 join t_stu t2 on (t1.id=t2.cla_id) where t1.id in (1,2,3);
内连接:直接使用join就是内连接。
左连接:left join
左连接是将左边的这张表设置为主表来连接右边的表,如果左边表中的数据在右表中没有出现,会自动使用null来替代。
select t1.name,count(t2.id) from t_cla t1 left join t_stu t2 on (t1.id=t2.cla_id) group by t1.id;
右连接
右连接是将右边的这张表设置为主表来连接左边的表,如果右边表中的数据在左表中没有出现,会自动使用null来替代。
select t1.name,count(t2.id) from t_cla t1 right join t_stu t2 on (t1.id=t2.cla_id) group by t1.id;