--使用xx数据库(xx为数据库名字),从而可以切换数据库
use xx;
本篇均以student表为例:
-- 查找:
-- 查找表中所有信息
select * from student;
-- 查找表中性别为男的
select * from student where sex="男";
设置查询范围:
-- = 等于
-- > 大于
-- < 小于
-- <= 小于等于
-- >= 大于等于
-- != <> 不等于
例:
-- 查找表中年龄为14的
select * from student where age = 14;
-- 查找表中年龄大于等于22的
select * from student where age >= 22;
-- 查找表中年龄大于20的
select * from student where age > 20;
-- 查找不等于22的
select * from student where age <> 22;
select * from student where age != 22;
-- 逻辑运算符
-- and 并且
-- or 或者
例:
-- 查找年龄大于22的男生
select * from student where sex="男" and age > 22;
select * from student where sex="nv" and age > 22 and name="www";
-- 查找年龄介于20和30之间的
select * from student where age > 22 and age < 49;
-- 也可以使用between and 相当于= 之间 [22,48]
select * from student where age between 22 and 48;
-- 查找年龄大于22或者是男生
select * from student where sex="男" or age > 22;
-- 查找年龄为34,22或者45的
select * from student where age=34 or age=22 or age=45;
-- in 表包含(可以使用in来实现查找年龄为34,22或者45 的)
select * from student where age in(34,22,45);
-- 查找id为1,4,5的(括号中顺序不影响查找结果)
select * from student where id in(1,5,4);
-- 模糊查询
-- like 为模糊查询,需要配合占位符使用
-- _代表一位字符
-- % 代表任意位字符
例:
查找姓张且名字为两个字的学生
select * from student where name like "张_";
查找名字第二个字为张且名字为三个字的同学
select * from student where name like "_张_";
-- 查看名字里有张的
select * from student where name like "%张%";
-- 分页查询(限制查询)
-- limit a,b 限制查询子语句 a代表起始索引值,起始索引值从0开始,b代表查询个数
-- litmit b offset a a代表起始索引值,起始索引值从0开始,b代表查询个数
例:
查询从第六个开始的前三个
select * from student limit 6,3;
select * from student limit 3 offset 6;
-- 如果有其他子语句,limit子语句放在最后位置
查找性别为男的学生中,从0开始的前两个
select * from student where sex='男' limit 0,2;
-- 排序
-- order by 列名 desc降序|asc升序(默认升序,asc可以省略)
例:
学生按年龄升序排列
select * from student order by age;
-- 或者
select * from student order by age asc;
学生按年龄降序排列
select * from student order by age desc;
学生按年龄升序排列 并从0开始显示前三个
select * from student order by age limit 0,3;
查找性别为女的学生,按年龄升序排列
select * from student where sex='女' order by age;
-- 聚合函数/分组函数
-- 聚合
-- sum求和
-- avg 取平均值
-- max 取最大值
-- min 取最小值
-- count 取得记录值(不会统计值为NULL的记录)
例:
-- 统计学生年龄总和
select sum(age) from student;
-- 查找最大的年龄
select max(age) from student;
-- 统计学生年龄平均值
select avg(age) from student;
-- 统计总共多少条信息
select count(*) from student;
-- 分组函数
-- group by
-- 分组后筛选用having
例:
-- 以班为单位查询男生平均年龄
select avg(age),class,sex from student where sex='男' group by class;
-- 查询1班男生平均年龄
select avg(age),class,sex from student where sex='男' group by class having class=1;
-- 插入
insert into student (name,sex,age) values("张一我","女",25);
insert into student (name,sex) values("张一","女");
-- 修改
update student set age=24 where name="www";
update student set name="吴千",age=29,sex="男" where id = 2;
-- 删除
delete from student where id=3;
注意:有的电脑的mysql软件需要保证修改和删除用where需要提到主键的值(否则报错1175),如果想要关闭这个功能,csdn有相应的解决方法,可自行查询)