select(基本查询)
select 字段名.... from 表名;
select *from 表名; //星号代表所有字段,但不推荐使用
排序查询
select 字段名.... from 表名 order by排序依据的字段 asc ;查询并排序默认是asc升序 desc降序。
select 字段名.... from 表名 order by 排序依据的字段 desc ;降序
select 字段名.... from 表名 order by 排序依据的字段 rand() ;随机排序(不推荐,建议小的尝试一下就行,做项目别用)
有条件的查询
select 字段名....from 表名 where 查询的条件 ;
select 字段名....from 表名 where where address like '%郑州%' and id=4;
限制行数查询
select 字段名....from 表名 limit 300;//只输出300行的数据,就算数据库有一万行也只输出300行,如果小于300行就全部输出 select 字段名....from 表名 limit 0, 8;//从索引0开始往后输出8行数据也就是从第一行开始输出8行。
查询表表的别名,列的别名
select son as 学号,name as 姓名 from student as st;
select son 学号 ,name 姓名 from student st;
给字段加别名,在输出的表格上就会显示出来设置的别名,表名也一样,而且有的表名太长容易写错,设个别名方便设计和使用
输出一列随机的0-10;
select 字段名.... round(rand()*10)from 表名 limit 0, 10;
同时查询输出多个表
select * from 表名1,表名2,表名3;
查询一个计算列
select 3*3+2, 字段名1,字段名2 from 表名;
in() 和 not in()
in()查询条件 in()是只要是符合括号里的数值或者字符就查询显示出来
select id '索引',sname '姓名',age '年龄',sex '性别',addr '地址'from student where id in(2,5,11);
not in()则和in()相反只要是不符合括号里的数值或者字符就查询显示出来
select id '索引',sname '姓名',age '年龄',sex '性别',addr '地址'from student where sname not in('张三丰','赵敏');
分页查询
分页查询显示第一页,每页3条 select son,sname from wx_student limt 0,3;
分页查询显示第二页,每页3条 select son,sname from wx_student limt 6,3;
分页查询显示第最后一页 select son,sname from wx_student limt 9,3;
查询页的高效写法 select son,sname from wx_student limt当前页数*每页条数-每页条数 , 每页条数;
多表查询
select * from 表名,表名;
select 1,2,3 ;
select * from (select 1,2,3) as t1 , (select 4,5,6) as t2; select * from stu s1,stu s2,stu s3;
select * from student; select * from teacher;
内连接*:join,inner join
join using 后面接 两张表中都存在的字段 (字段名称 一样) join on 后面接 两张表中中需要关联的字段 (字段名称不需要一样 a.id = b.id ) */ select * from student join teacher using(stid)
select * from student a join teacher b on a.id=b.id;
select * from emp e inner join dept d on e.depton=b.depton;
内连接 只把join后面的表与join前的表相对应的数据给予
外连接
左连接
select * from emp e left join dept d on e.depton=b.depton;
左连接:右边的表不管左边有没有相对应的数据都把所有的数据全部给左边的表
右连接
select * from dept d right join emp eon e.depton=b.depton;
右连接:和左连接正好相反,显示右侧表的全部内容,不管左侧表是否有其对应的记录。使用方法和左连接一样。