MySQL Code Snippet

2023-08-23 18:44:25 浏览数 (1)

Tips SQL

代码语言:javascript复制
-- 追踪优化器 Trace 功能
--  optimizer_trace_enabled=1
--  optimizer_trace_file=optimizer_trace.log
SELECT @@optimizer_trace;
SET optimizer_trace = 'enabled=on';
-- <your query>;
SET optimizer_trace = 'enabled=off';
select * from INFORMATION_SCHEMA.OPTIMIZER_TRACE;


-- 查看优化后的 SQL
-- 在联表查询时比较有效果
EXPLAIN <你的 SQL>;
SHOW WARNINGS;


-- 查看处理
SHOW PROCESSLIST;


-- 查看表结构
DESC user;

Function

代码语言:javascript复制
-- https://www.w3schools.com/sql/func_mysql_find_in_set.asp
select FIND_IN_SET('bb', 'aa,bb,cc');
select FIND_IN_SET(null, '0');

ON vs USING

MySQL ON vs USING? | stackoverflow

删除重复数据

代码语言:javascript复制
DELETE
FROM
  student
WHERE
  id NOT IN (
  SELECT
    id
FROM
  ( SELECT MIN( id ) AS id FROM student GROUP BY `name` ) tmp)

要多加一层 tmp 包装,否则会遇到:1093 - You can't specify target table 'student' for update in FROM clause

备份表

代码语言:javascript复制
-- 创建同结构备份表
create table zzz_my_table_220727 like my_table;
-- 将需要数据写入备份表
insert into zzz_my_table_220727 select * from my_table ORDER BY id desc LIMIT 1000;
-- 情况原表
truncate table my_table;

SQL AND OR 执行优先级

代码语言:javascript复制
select id from table01 where condition1 or condition2 and condition3;

-- 等价于:
select id from table01 where condition1 or (condition2 and condition3);
-- 而非:
select id from table01 where (condition1 or condition2) and condition3;

and 级别高于 or。相当于可以把 and 看成 乘号 *,把 or 看成 加号

References

  • 编程小技巧(3):查看优化后的 SQL

– EOF –

  • # mysql

0 人点赞