MySQL 寫SQL語句的幾個習慣

2021-10-19 15:59:40 字數 1557 閱讀 9286

1.設計表時 加注釋及欄位編碼格式、排序規則及主鍵、建立時間、更新時間

create table `attribution_home`  (

`id` int(11) not null auto_increment comment '主鍵id',

`attribution_home` varchar(255) collate utf8_unicode_ci default null comment '歸屬地',

`create_time` datetime default current_timestamp comment '建立時間',

`update_time` datetime default null comment '修改時間',

primary key (`id`) using btree

) engine = innodb default charset=utf8 collate=utf8_unicode_ci row_format=dynamic comment='歸屬地表';

2.執行update/delete時 盡量加乙個limit

首先會提高執行效率,因為不加limit會全表掃瞄;其次若是刪除資料量很大,則會出現cpu爆滿的狀況,並會越刪越慢;

delete from test where id=1 limit 1;

update test set name='xiaozhan' where id=1 limit 1;

3.insert語句 新增字段說明

insert into `attribution_home` (`attribution_home`) values ('安徽');

4.刪除資料之前先備份,在進行刪除!!!

5.where後面的字段 注意欄位的轉換  尤其是varchar與int型別,''的使用

select id,name from test where id=1;

select id,name from test where id='1';

6.查詢字段 替換*

select id,name from test where id=1;

select * from test where id='1';

7.盡量使用varchar代替 char

8.修改字段資訊時 請及時更新字段注釋

alter table org_user_center add column  create_time datetime null default current_timestamp comment '建立時間' ;

9.索引命名要規範,主鍵索引名為 pk_ 欄位名;唯一索引名為 uk _欄位名 ;普通索引名則為 idx _欄位名。

習SQL語句之SQL語句大全

語 句 功 能 資料操作 select 從資料庫表中檢索資料行和列 insert 向資料庫表新增新資料行 delete 從資料庫表中刪除資料行 update 更新資料庫表中的資料 資料定義 create table 建立乙個資料庫表 drop table 從資料庫中刪除表 alter table 修...

mysql語句如何寫排名 用sql語句寫排名

使用sql語句求排名 表jh03有下列資料 name score aa 99 bb 56 cc 56 dd 77 ee 78 ff 76 gg 78 ff 50 1.名次生成方式1 score重複時合併名次 select place select count distinct score from ...

mysql批量替換的SQL語句怎麼寫

先看一下分頁的基本原理 我拿的是csdn那個百萬級資料庫來測試!select from csdn order by id desc limit 100000,2000 耗時 0.813ms 分析 對上面的mysql語句說明 limit 100000,2000的意思掃瞄滿足條件的102000行,扔掉前...