MySQL学习记录(第四周)20211115-20211121

173 阅读2分钟

2021年11月15日

子查询可以使用max,avg,sum,使用两端查询,eg找出销售量最大的数据:

select * from tb where sales in (select max(sales) from tb);

eg找出大于平均年龄的数据

select * from tb1 where age >= (select avg(age) from tb1);

2021年11月16日

子查询和内连接相似但有区别:

  • 子查询包含去重功能
select empid,name from tb1 where empid in (select empid from tb);
  • 使用distinct的自连接与子查询相同
select distinct tb1.empid,tb1.name from tb join tb1 on tb1.empid=tb.empid;

2021年11月17日

关于用子查询,筛选两个表中的连接键中的相同项、不同项,主查询和子查询不能使用相同的表:

  • 使用相同的表:
select * from tb1 where exists (select * from tb1 where tb.empid=tb1.empid);

以上输出ERROR 1054 (42S22): Unknown column 'tb.empid' in 'where clause'

  • 只要有使用不同的表才行:
select * from tb1 where exists (select * from tb where tb.empid=tb1.empid);

输出tb1中tb和tb1中都有empid

2021年11月18日

  1. 复制表和复制表的结构区别:
  • 复制表
create table 新表 like 旧表;
  • 复制表的结构
create table 新表 select * from 旧表;
  • 增加列
alter table test_tb add rank int auto_increment primary key first;
  • 删除列
alter table test_tb drop column rank;
  1. cmd没有光标解决,切换中文后输入几个中文,再切换输入中文。
  2. 利用子查询,向test_tb填充,rank自动排序。
insert into test_tb
    (empid,sales,month)
(select 
    empid,sales,month
from tb 
    order by sales desc);

2021年11月21日

  • 在使用exists方法的时候,需要注意from的表是哪个表,题目中是从表tb中提取tb1中存在的记录,所以主查询时from查tb表,子查询时from查tb1表,代码如下:
select * 
    from tb
where exists
    (select * from tb1 where tb.empid=tb1.empid);