MySQL数据表中的数据操做

一、插入数据sql

insert into t_user (username,password,nickname) values ('foye','123','佛爷');

如下方式必须写出全部的字段函数

insert into t_user values (null,'eryuehong','456','二月红');

能够经过 insert into xxx select xxx 插入已有表中的数据code

insert into t_user(username,nickname) select no,name from t_student;

二、简单查询排序

select * from 表名table

查询条件class

select * from 表名 where 条件date

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='二月红';

三、更新select

update 表名 set 字段名=新的值 where 条件im

update t_user set username='baye',nickname='八爷' where id=2;

四、删除统计

delete from 表名 where 条件

delete from t_user where id=1;

使用truncate能够清空表中的所有信息,并且能够将自动递增的标识清空

truncate table t_student;

五、经常使用查询

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常常使用)

六、跨表查询(链接查询)

一、相对较早的方式

select * from t_cla t1,t_stu t2 where t1.id = t2.cla_id and t1.id in (1,2,3);

较早的方式是经过where来链接几个主键和外键的。

二、目前经常使用的方式

经常使用的方式是使用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;

相关文章
相关标签/搜索