博主最近临近实习风口,在学校抓紧复习学习了一下mysql 查询的基础语句,总结了一下。
select concat(name,'=>',score) from student;
#在什么之间(a和b之间的数据,包括a和b)
select * from student where id between 1 and 3;
select * from student where age = (select max(age) from student);
#查询出包含的数据
select * form student where id in(1,2,3,4);
字段名较长可以使用,最主要是保证数据库安全,可以取表的别名和字段的别名。(下面的语句是给count(*)取了一个别名)
select COUNT(*) as num, class_name from student GROUP BY class_name;
分组统计,根据某个字段将所有的结果分类,并进行数据统计分析 如果一个sql语句中同时存在group by和where子句,那么group by一定在where之后。分组和统计不会分离,有统计就有分组,有分组就有统计.
统计函数:AVG()、SUM()、MAX()、MIN()、COUNT();
#统计每个班级的人数
select COUNT(*) as num, class_name from student GROUP BY class_name;
#统计每个班的男女人数
select COUNT(*) as num , class_name as bj, sex from student GROUP BY class_name,sex;
一般在多分组时使用,指你在对一个班级进行男女人数进行统计时,又要对班级人数进行统计。
#统计每个班男女人数,并且统计每个班的人数(回溯统计),
#下面出现了GROUP_CONCAT(name)这个字段意义不大可以省略
select COUNT(*) as num, class_name as bj , sex, GROUP_CONCAT(name) as name from student
GROUP BY class_name , sex WITH ROLLUP;
#统计每个班级的人数并升序排序
select COUNT(*) as num , class_name as bj FROM student GROUP BY class_name asc;
#查出班级人数小于3的班级(having)
SELECT COUNT(*) , class_name FROM student GROUP BY class_name HAVING COUNT(*)<=3;
#避免count重复,查出班级人数小于3的班级,可以去掉前面的count
SELECT class_name FROM student GROUP BY class_name HAVING COUNT(*)<=3;
#对年龄降序排序
select * from student ORDER BY age desc;
#多字段排序,先按照性别降序,在按照年龄升序
select * from student ORDER BY sex desc ,age asc;
#获取表中前3条数据
select * from student limit 3;
#获取表中第3条数据之后的4条数据
select * from student limit 3 ,4;
联合查询是指针对结果的合并(多条select语句合并)
all:保留所有记录
distinct:去重重复记录(默认)
语法:select 查询 union 查询选项 slect 查询
#联合查询,查询两个表的所有记录(默认去重)
select * from student union all select * from student2;
#去重
select * from student union distinct select * from student2;
#只需要看student中的姓名和student2的年龄数据(数据不能对应,这样查询无意义)
select name from student union all select age from student2;
#如果使用where进行筛选(若要全部有效,在每个select加入where条件)
select * from student union all select * from student2 where age <18;
#联合查询并且按照年龄排序(一个order by针对所有slect进行排序)
select * from student union all select * from student2 order by age desc;
#交叉连接(笛卡尔积,这种链接无意义)
select * from student cross join student2;
*内连接:inner join (用的多)
内连接语法:左表 join 右表 on 连接条件
内连接inner JOIN,
#获取已经选择专业的学生信息,包括所选专业
select s.*,c.name as course_name from t_stu as s inner join t_course as c on s.course_no = c.id;
*外连接:左外连接和右外连接(用的多)
左外连接:left join
#查询所有学生信息,包括他们的专业
select s.*,c.name as course_name from t_stu as s left join t_course as c on s.course_no = c.id;
右外连接:right join
#右外连接,查询这个专业里的所有学生信息
select s.*,c.name as course_name from t_stu as s right join t_course as c on s.course_no = c.id;
*自然连接(使用很少)
用来简化同名字段的链接条件行为
#查询所有学生信息,包括他们的专业
select s.*,c.c_name from t_stu s left join t_course c using(c_id);
select * from t_stu s left join t_course c using(c_id);
未完待续