code格式规范:
所有关键字大写,关键字右边对齐,子句缩进
列名最好和表中的列名一样(大小写一样)
SELECT name
FROM customer C
WHERE C.id NOT IN ( SELECT C1.id
FROM customer C1
WHERE C1.referee_id = 2 );
参考资料:
官方文档:【参考:MySQL :: MySQL 5.7 参考手册 :: 13 SQL 语句】
【参考:SQL中的谓词 - 知乎】
题目以类型归类,记录常用且易错的类型
SQL基础
百度:SQL执行顺序
【参考:sql语句的执行顺序以及流程_sql执行顺序_۩ﺴ往后余生ﺴ۩的博客-CSDN博客】
IS NULL
【参考:584. 寻找用户推荐人 【比官方细,千字干货!】(三值运算,NULL) - 寻找用户推荐人 - 力扣(LeetCode)】
【参考:584. 寻找用户推荐人 - 简单 - 力扣(LeetCode)】
SELECT name FROM customer WHERE referee_id != 2 OR referee_id IS NULL;
多表查询
【参考:183. 从不订购的客户 - 力扣(LeetCode)】
- 子查询
select customers.name as 'Customers' # as 别名
from customers
where customers.id not in
(
select customerid from orders
);
# 先从orders中找出customerid
SELECT c.Name as Customers
FROM Customers as c
left join Orders as o on c.Id=o.CustomerId
where o.Id IS NULL
IF 表达式
IF( expr1 , expr2 , expr3 )
【参考:1873. 计算特殊奖金 - 力扣(LeetCode)】
【参考:MySQL, 7种解法 - 计算特殊奖金 - 力扣(LeetCode)】
SELECT
employee_id,
IF(
employee_id%2=1 and name not like 'M%',
salary,
0
) as bonus
FROM Employees
ORDER by employee_id
UPDATE Salary set sex=IF(sex='f','m','f')
CASE WHEN END
UPDATE salary
SET
sex = CASE sex
WHEN 'm' THEN 'f'
ELSE 'm'
END
自连接
【参考:196. 删除重复的电子邮箱 - 力扣(LeetCode)】
【参考:对「官方」题解中 “delete” 和 “>” 的解释,推荐! - 删除重复的电子邮箱 - 力扣(LeetCode)】
2、p1.Id > p2.Id
继续之前,先简单看一下表的连接过程,这个搞懂了,理解WHERE条件就简单了👇
a. 从驱动表(左表)取出N条记录;
b. 拿着这N条记录,依次到被驱动表(右表)查找满足WHERE条件的记录;
DELETE p1
FROM Person p1,
Person p2
WHERE
p1.Email = p2.Email AND p1.Id > p2.Id
正则
【参考:1527. 患某种疾病的患者 - 力扣(LeetCode)】
^DIAB1表示以DIAB1开头
|表示或者
.表示一定有任意一个字符
*表示重复0到无穷多个的前一个字符
第一个\表示转义字符
\s是指空白,包括空格、换行、Tab 缩进等所有的空白
所以.*\sDIAB1表示DIAB1前是空格且空格前有0到无穷多个的任意字符
# Write your MySQL query statement below
select patient_id,
patient_name,
conditions
from Patients
where conditions rlike '^DIAB1|.*\\sDIAB1'
函数
upper lower
【参考:1667. 修复表中的名字 - 力扣(LeetCode)】
【参考:【JMao】简单函数解法+分享刷题经验 - 修复表中的名字 - 力扣(LeetCode)】
# Write your MySQL query statement below
SELECT user_id,
CONCAT(Upper(Left(name,1)),Lower(substring(name,2))) as name
from Users
order by user_id
concat
【参考:1484. 按日期分组销售产品 - 力扣(LeetCode)】
【参考:mysql 分组拼接函数 group_concat - 按日期分组销售产品 - 力扣(LeetCode)】
SELECT sell_date,
count(distinct product) as 'num_sold',
# 组内拼接
group_concat(distinct product # 去重
order by product asc # 分组,按照字典序升序
separator ',') # 间隔
as 'products'
from Activities
group by sell_date
order by sell_date
union all
union和union all都可以起到关联结果集的作用,区别在于:
- union会自动去除关联的两个结果集中的重复数据,
- union all则不会主动去除两个结果集中的重复数据,会展示所有的数据;
列转行
【参考:1795. 每个产品在不同商店的价格 - 力扣(LeetCode)】
【参考:表格-列转行 - 每个产品在不同商店的价格 - 力扣(LeetCode)】
# Write your MySQL query statement below
select product_id, 'store1' as store, store1 as price
from Products where store1 is not null
union all
select product_id, 'store2' as store, store2 as price
from Products where store2 is not null
union all
select product_id, 'store3' as store, store3 as price
from Products where store3 is not null;