SQL 语句 增删改查、边学习边增加中..... 这一部分为select

发布时间 2023-10-11 11:27:41作者: 修炼诗人

SQL语句按照最大的类别分为

  1、增加 insert 

  2、删除 delete  https://www.cnblogs.com/kuangmeng/p/17756654.html

  3、修改update

  4、查询 select : https://www.cnblogs.com/kuangmeng/p/17756425.html

这一部分为select 查询操作,以及对应的Leecode题,进行加深印象。通常  select * from 表名 ,这条SQL语句代表查询表名的所有数据。

175. 组合两个表    

联合两个表进行查询,本人采用的是下面SQL ,但是返回的是 Person.personId = Address.personId 的数据, 与题目中要求 Person表中的数据,如果没有在Address表中出现,city,state 字段变为null

select firstName,lastName,city,state  
from Person,Address  
where Person.personId = Address.personId

所以采用 left join 、 on 的方式。

其中 left join :是一种连接(JOIN)操作,用于将两个或多个表根据某个相关列进行关联。LEFT JOIN会返回左表中的所有记录,以及右表中与左表匹配的记录。如果在右表中没有找到匹配的记录,则会返回NULL值

其中 on:ON子句用于指定连接条件,即哪些列需要相等才能将两个表关联起来。

181. 超过经理收入的员工   

题目:给定一个表,采用别名as的形式,提取两次表中的数据。

select a.name as 'Employee'  ##### 将a.name 设置别名 为Employee 符合题目要求

select a.name as 'Employee' 
from Employee as a,Employee as b 
where a.managerId = b.id  and a.salary>b.salary 

其中 whereand,将两个判断条件连接。

182. 查找重复的电子邮箱

重复字段,暂时采用unique 唯一标识字段  思考再三之后,决定采用group by   +  count 值

count : 遍历表,找到对应字段出现的次数。

group by:若是没有 加后续条件,则按照降序排列。

having:对group by字段添加 附属条件

select email as 'Email'
from Person
group by email
having count(email) > 1;

183. 从不订购的客户

没有出现的用户,根据题目来说,目前的见解,只能采用 not in。

其中not in : 顾名思义   a not in b  ==> 返回所有a 有b 没有的东西。

整体上,将select内置到 not in中。通过相同的字段与字段进行判断。

select name as 'Customers'
from Customers
where  Customers.id not in 
( select customerId from Orders);