MySQL leetcode刷题随记

1、or vs union

对于单列来说,用or是没有任何问题的,但是or涉及到多个列的时候,每次select只能选取一个index,如果选择了area,population就需要进行table-scan,即全部扫描一遍,但是使用union就可以解决这个问题,分别使用area和population上面的index进行查询。 但是这里还会有一个问题就是,UNION会对结果进行排序去重,可能会降低一些performance,所以最佳的选择应该是两种方法都进行尝试比较。

stackoverflow:https://stackoverflow.com/questions/13750475/sql-performance-union-vs-or

2、<=> and is null

判断时如果比较值中有NULL会跳过,如果是<=>安全等于,就可以判断NULL。或者加上or 判断值 is null

 3、not in的效率较低尽量不要使用

#183从不订购的顾客:https://leetcode.cn/problems/customers-who-never-order/description/

select Name as 'Customers' from Customers where Id not in( select CustomerId from Orders );

改为左连接:

select Name as 'Customers' from Customers left join Orders on Customers.Id = Orders.CustomerId where Orders.Id is null

4、if语句

MySQL中if语句用法:if(expr1,expr2,expr3) expr1为true时,则返回值为expr2,expr1为false时,则返回值为expr3。

5、变量重命名:as

6、输入答案记得排序order by

7、更新

update <表名> set 字段1=值1, 字段2=值2 where

8、删除

delete注重删除数据,drop注重删除结构

delete p1

from Person p1,Person p2

where p1.email=p2.email and p1.id>p2.id;
9、mysql中字符串相关函数
更改姓名首字母大写,其余小写
concat连接字符串
upper大写,lower小写
left()取左侧,right()取右侧
select user_id,
concat(upper(left(name,1)),lower(right(name,length(name)-1))) as name
from Users
order by user_id
10、
count计数
distinct唯一
group_concat(distinct product order by product separator',')连接,第一个参数:连接的字符,第二个参数:连接的分类,第三个参数:连接用什么分割
group by分类
select sell_date,
  count(distinct product)num_sold,
  group_concat(
    distinct product
    order by product
    separator',')products
from Activities
group by sell_date
order by sell_date
11、like
匹配字符串:可包含%:省略的字符串模板 空格
 
posted @ 2023-03-21 21:59  feifei102  阅读(32)  评论(0)    收藏  举报