MySQL查询条件,多表查询
2021/7/31 19:39:00
本文主要是介绍MySQL查询条件,多表查询,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
MySQL
查询条件之having
# having的功能与where一样 where 在分组之前用, where中写的条件必须在表中存在 having 在分组之后用 # 查询每个部门中大于30岁的平均工资,并且,保留中平均工资在10000以上的 select post, avg(salary) as avg_salary from emp where age > 30 group by post having avg(salary) > 10000;
查询条件之distinct
# 去重的前提条件:数据必须一毛一样 # 有主键存在,没必要去重 # 去重年龄 select dictinct age from emp;
查询条件之order by
select * from emp order by salary; # 默认是升序排列 select * from emp order by salary asc; # 升序,可以不指定,建议指定 select * from emp order by salary desc; # 排序还可以指定多个字段进行排序 select *from emp order by age, salary desc ; # 查询每个部门中大于30岁的平均工资,并且,保留中平均工资在10000以上的, 按照平均工资降序排列 select post, avg(salary) as avg_salary from emp where age > 30 group by post having avg(salary) > 10000 order by avg(salary) desc;
查询条件之limit
分页,限制数据 select *from emp limit 5; # 限制前5条数据 select *from emp limit 5, 5; # 从第5条开始,查询5条数据 # 查询工资最高的员工 select max(salary) from emp; select * from emp order by salary desc, age asc limit 1;
多表查询
1. 子查询, 一个SQL语句的结果作为另外一个SQL的条件 # 查询egon所在的部门 1) 查询egon所在部门的id select dep_id from emp where name='egon'; 2) 在拿着dep_id取dep表中查询部门名称 select * from dep where id = (select dep_id from emp where name='egon'); 2. 连表查询, 将多个表拼接成一张表,当成单表查询 select *from emp,dep; select * from emp,dep where emp.dep_id=dep.id; # inner join 内连接 select * from emp inner join dep on emp.dep_id=dep.id; # left join 左连接 以左表为基表,查询出左表的所有数据,右表的数据用null填充 select * from emp left join dep on emp.dep_id=dep.id; # right join 右连接 以右表为基表,查询出右表的所有数据,左表的数据用null填充 select * from emp right join dep on emp.dep_id=dep.id; # union 全连接 select * from emp left join dep on emp.dep_id=dep.id union select * from emp right join dep on emp.dep_id=dep.id;
数据库练习题大礼包(能做几道是几道 内附答案) https://www.cnblogs.com/Dominic-Ji/p/10875493.html
这篇关于MySQL查询条件,多表查询的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-09-15一文看完MySQL 9.0新特性!
- 2024-09-10MySQL分库分表教程:入门级解决方案与实践
- 2024-09-10MySQL教程:初学者的入门指南
- 2024-09-10MySQL教程:从零开始入门的步骤与实践
- 2024-09-10MySQL慢查询教程:轻松掌握优化技巧
- 2024-09-10MySQL慢查询教程:快速提升数据库性能的入门指南
- 2024-08-27mysql ddl常用的方法和语句-icode9专业技术文章分享
- 2024-08-13MySQL入门:轻松掌握数据库基础操作与技巧
- 2024-08-12Seata和Mysql存储演示学习入门:初级开发者实战指南
- 2024-08-10从 MySQL 迁移到 TiDB:使用 SQL-Replay 工具进行真实线上流量回放测试 SOP