MySql碎片

1、使用B表填充A表
Insert into TableA (columnA1,columnA2....) Select columnB1,columnB2....From TableB where contions=....
从表中复制数据到现有表中,现有表中任何存量数据都不会受影响,需注意字段对应一致,同时注意与select into的区别

select into:从一张表复制数据,插入到一张新表中,可用来创建新表(空表)
Select into newTable [in externalDB] From tableA;
可添加where子句,使查询返回无数据。
select * into newtable from TableA where 1=0;

2、创建索引
Create Index index-name On Table-name (Column-name);
Create Unique Index index-name On Table-name (Column-name);
Alter Table table-name Drop Index index-name;

3、执行A表N次,遍历循环外表B
Select * From tableNameA A where Exists
(select * From tableNameB B where A.columnX=B.columnX)
不使用not in是因为走全表扫描,会不走索引,而not exists依然会走索引,执行效率更高

4、order by查询的字段,在遇到相同值的时候,无法保证稳定的排序,尤其在带limit时,返回的可能是不同结果集。
解决办法:order by的时候增加一个唯一字段作为第二排序字段

5、强制使用索引 force index
MYsql写法:select * from table-name Force index (index-name) where conditions(含 index-name=xxx)
Oracle写法:select /+index(表名 空格 索引名)/ * from table-name ....
注:/...../ 第一个星星后无空格,如果表用了别名,则在注释里的表也要使用别名

多表左连接查询时,若where条件中有字段为非索引字段,会导致该字段所在的表进行全表扫描,从而导致效率大大下降,此时便可增加强制索引

6、多表联合更新
Update A表 SET A表.目标更新字段1=B表.源数据字段1,A表.目标更新字段2=B表.源数据字段2
FROM B表 where A表.xxxx=B表.xxxx

7、从查询结果中设置变量
select @group:='group' from A where id=1;
使用@+变量名+':='+查询结果字段

8、删除表数据时使用别名
直接使用别名会报错,如:Delete from tableName t where t.id=1;
//报错:have an error in sql syntax
但在使用别名时,多写一个别名在delete关键词后面,则不再报错。连接查询也可以同时删除多张表内的数据。
Delete t from tableName t where t.id=1;
// OK

posted @ 2026-06-08 10:37  愿鲁且愚  阅读(7)  评论(0)    收藏  举报