mysql之表查询

表查询之关键字之limit

# 1.limit   分页
1.只跟一个数字
  select * from db limit 5; # 从头开始展示几行数据(5行为一页)
    2.跟两个数字
  select * from db limit 5,5# # 第一个是起始位置 第二个是几行数据
       
# # 求薪资最高的员工所有数据
1.先按照薪资降序排序
   2.在使用limit限制取一行
   select * from emp order by salary desc limit 1;

表查询之关键字之regexp正则

select * from emp where name regexp '^j.*(n|y)$';   # 匹配以j开头,以n或者y结尾的名字


# 补充:

关键字:exists

"""
EXISTS关字键字表示存在。在使用EXISTS关键字时,内层查询语句不返回查询的记录,
而是返回一个真假值,True或False。
当返回True时,外层查询语句将进行查询
当返回值为False时,外层查询语句不进行查询。

"""

   select * from emp
       where exists
      (select id from emp where id > 3);

   select * from emp
       where exists
      (select id from emp where id > 250);
       
       
 # 如果exist后面的条件成立,才会执行前面的命令,不成立就不会执行

多表查询的两种方法

# 数据准备
#建表
create table dep(
   id int primary key auto_increment,
   name varchar(20)
);

create table emp(
   id int primary key auto_increment,
   name varchar(20),
   sex enum('male','female') not null default 'male',
   age int,
   dep_id int
);

#插入数据
insert into dep values
(200,'技术'),
(201,'人力资源'),
(202,'销售'),
(203,'运营');

insert into emp(name,sex,age,dep_id) values
('jason','male',18,200),
('tony','female',48,201),
('kevin','male',18,201),
('nick','male',28,202),
('owen','male',18,203),
('jerry','female',18,204);

多表查询方法之连表查询

# 连表操作
先将查询涉及到的表拼接成一张大表 之后基于单表查询

# 笛卡尔积
select * from emp,dep;
   select * from emp,dep where dep_id=id;
   select emp.name,dep.name 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    全连接:展示左右两表中所有的数据没有对应则NULL填充
  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;

多表查询方法之子查询

# 子查询:其实就是分步操作
将一张表的查询结果当做另外一条SQL语句的查询条件

1.查询部门是技术或者人力资源的员工信息
1.先查询技术和人力资源的部门编号
  select id from dep where name in ('技术','人力资源');
   2.根据部门编号去员工表中筛选出对应的员工数据
  select * from emp where dep_id in (200,201);
   '''子查询:将SQL语句括号括起来即可充当查询条件'''
   select * from emp where dep_id in (select id from dep where name in ('技术','人力资源'));

 

 

posted @ 2021-11-20 15:07  一叶松  阅读(62)  评论(0编辑  收藏  举报