e from 表名 where id > 10 or name = 'name1';
4.select id,name as 新名称 from 表名 where id > 10 or name ='nam1';
原表格:
执行后:
5.select name,age,'数据' from 表名;
原表格:
执行后:
其他:
原表:
1.select * from t1 where id != 1;
执行结果:
2.select * from t2 where id in (1,3,4);
执行结果:
3.select * from t1 where id not in (1,4);
执行结果:
4.select * from t1 where id between 1 and 4; --->[1,4]
执行结果:
5. select * from t1 where id in (select score from t2);
t2表:
执行结果:
通配符:
'%':例如a%,a的后面可以去取任意个数的字符
'_':例如a_,a的后面只能取一个任意字符
1.select * from t1 where name like 'ro%';
执行结果:
2.select * from t1 where name like 'root_';
执行结果:
限制:
比如说你去通过百度、谷歌查资料,它后面会给你分页,一次看十条二十条,这样不会让电脑资源不够导致崩溃。
原表格:
1.select * from t1 limit 6;
执行结果:
2.select * from t1 limit 2,5;
这里的2代表起始位址,5代表一共查几笔资料
执行结果:
3.select * from t1 limit 10 offset 20;
这里表示从20开始,往后查10条数据
执行结果:
如果要查找后面10笔数据就要先把整笔数据进行翻转再去查这10笔即可
排序:
从大到小查:
1.select * from t1 order by id desc;
利用id去进行从大到小排列数据,执行结果:
从小到大查:
2.select * from t1 order by id asc;
利用id去进行从小到大排列数据,执行结果:
查后5笔数据:
多列排序:
按排列优先顺序去排,先把score按从大到小的方式排列,如果有score相同再去按它的id从小到大的方式排列
组合:
以员工和部门作为例子,先创建部门表:
再创建一个员工表:
添加员工信息和部门信息:
查看添加好的员工信息表和部门信息表:
1.select part_id from userinfo group by part_id;
执行结果:
2.select max(id),part_id from userinfo group by part_id;
执行结果:
3.select min(id),part_id from userinfo group by part_id;
执行结果:
4.select count(id),part_id from userinfo group by part_id;
执行结果:
5.select sum(id),part_id from userinfo group by part_id;
执行结果:
6.select avg(id),part_id from userinfo group by part_id;
执行结果:
7.select count(id),part_id from userinfo group by part_id having count(id) > 1;
如果对于聚合函数结果进行二次筛选时就必须要用到having关键字,执行结果:
8.select count(id),part_id from userinfo where id = 1 or id < 4 group by part_id having count(id) > 1;
执行结果:
连表操作:
1.select * from userinfo,department where userinfo,part_id = department_id;
把两张表进行一个连接操作,如果后面不加条件就会出现混乱。执行结果:
2.select * from userinfo left join department on userinfo.part_id = department.id;
这种方法按以前SQL版本效能上会有差异,但现在其实没有太大的相差,但推荐使用这一个去进行表的连接。特点:左边的表userinfo会全部显示。执行结果:
3.select * from userinfo right join department on userinfo.part_id =department.id;
特点:右边表department的数据会全部显示
4.select * from userinfo inner join department where userinfo.part_id = department.id;
如果一个表连另外一张表的数据时,出现NULL时,就会把整行数据给隐藏掉