MySql建表與索引

2021-07-06 01:47:55 字數 2950 閱讀 9324

常用命令

show databases; //檢視資料庫

create database test; //建立資料庫

usetest;//選擇資料庫

\s//檢視資料庫狀態

? create table; //建立表的幫助

show tables; //檢視表

desc test; //檢視表結構

\c//退出建立表

一、建立表的基本模型(為可選的):

create table [if not exists]表名稱(

欄位名1 列型別 [屬性] [索引],

欄位名2 列型別 [屬性] [索引],

...欄位名n 列型別 [屬性] [索引]

)[表型別] [表字符集];

表名稱和欄位名需要我們自己定義名稱。

二、資料值和列型別:

細分都是按空間大小來區分的。

1、數值型

整形(整數)

非常小的整型 1位元組 tinyint

較小的整型 2位元組 smallint

中等大小的整型 3位元組 mediumint

標準的整型 4位元組 int

大整型 8位元組 bigint

浮點型(小數)m為位數,d為小數點保留幾位

float(m,d) 4位元組

double(m,d) 8位元組

定點數decimal(m,d) m+2位元組

2、字元型

char(m) 255 屬於固定長度字串

varchar(m) 255 可變長度字串

3、日期型

date   yyyy-mm-dd

time    hh:mm:ss

datetime    yyyy-mm-dd hh:mm:ss

timestamp   yyyymmddhhmmss

year    yyyy

時間儲存最好採用int型別,因為它可以參與運算。

三、資料字段屬性:

1、unsigned 可以讓空間增加一倍,如果不希望在字段中插入負值就使用此屬性,另外只能用在數值型字段。

2、zerofill 只能用在數值型字段,前導0(例如id int(5) zerofill,如果插入資料為11,會自動儲存為00011),該欄位自動應用unsigned。

3、auto_increment 只能是整數,資料每增加一條就會自動增1,欄位的值不允許重複。

4、null和not null 控制字段插入資料是否可以為空值。

5、default 預設值。在某個表裡,某個欄位不插入值的話,就會啟用預設值。

create table users(

id int unsigned not null auto_increment primary key,

name varchar(30) not null default '',

height double(10,2) not null default 0.00,

age int not null default 0,

*** char(4) not null default '男'

);四、建立索引:

1、主鍵索引

主要作用是確定資料庫表裡一條特定資料記錄的位置。

最好為每一張資料表定義為乙個主鍵索引。

乙個表只能指定乙個主鍵,主鍵的值不能為空。

指定主鍵有2種方法:

(1)create table users(

id int unsigned not null auto_increment primary key

);(2)

create table users(

id int unsigned not null auto_increment,

primary key(id)

);2、唯一索引

unique

它和主鍵索引一樣,都可以防止建立重複的值,不同的是,每個表可以有多個唯一索引。

3、常規索引

最重要的技術,提高資料庫效能,索引優化首先考慮常規索引。

查詢提高了,增刪改減慢了。

key和index是同義詞,用哪個都可以。

建立方法:

單獨建立常規索引:

create index 索引名稱 on 表名(欄位名,多個用逗號分隔);

刪除:drop index 索引名稱 on 表名;

建立表時建立常規索引:

create table users(

id int unsigned not null auto_increment primary key,

uid int not null,

index 索引名稱(uid));

4、全文索引

fulltext型別索引,只能在myisam表型別上使用,只有在varchar,char,text等文字字串上使用,也可以多個資料列使用。

create table books(

id int,

bookname varchar(30),

price double,

detail text not null,

fulltext(detail,bookname),

index ind(price),

primary key(id)

);正常查詢:select * from books where bookname like '%php%';

全文索引查詢:select bookname,price from books where match(detail) against('php');

以上兩種查詢來比,全文索引查詢效率比較高。

mysql建表建索引6 mysql建表建索引

建表 create table sj projects id int 11 not null auto increment,title varchar 255 not null default comment 專案名稱 platform id int 11 not null default 0 co...

mysql建表建索引6 Mysql建表 建立索引

建立表時可以直接建立索引,這種方式最簡單 方便。其基本形式如下 create table 表名 屬性名 資料型別 完整性約束條件 屬性名 資料型別 完整性約束條件 屬性名 資料型別 unique fulltext spatial index key 別名 屬性名1 長度 asc desc uniqu...

Mysql建表 建立索引

建立表時可以直接建立索引,這種方式最簡單 方便。其基本形式如下 create table 表名 屬性名 資料型別 完整性約束條件 屬性名 資料型別 完整性約束條件 屬性名 資料型別 unique fulltext spatial index key 別名 屬性名1 長度 asc desc uniqu...