MySQL随记

发布时间 2023-03-22 21:13:21作者: feifei102

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;