1. 程式人生 > 其它 >MySQL資料表基本操作{記錄2}{建立資料表}

MySQL資料表基本操作{記錄2}{建立資料表}

1,建立資料表:使用CREATE TABLE語句

CREATE TABLE 表名 (
    列名 列型別 欄位屬性,
    列名 列型別 欄位屬性,
    PRIMARY KEY ( `定義為主鍵的列名` )
)ENGINE=設定儲存引擎 DEFAULT CHARSET=設定編碼;

 例1:在work中建立表offices,結構如下

欄位名

資料型別

主鍵

外來鍵

非空

唯一

officecode

int(10)

city

int(11)

address

varchar(50)

country

varchar(50)

postalcode

varchar(25)

 

1 CREATE TABLE offices(
2 officecode INT(10),
3 city INT(11) NOT NULL,
4 address VARCHAR(50),
5 country VARCHAR(50) NOT NULL,
6 postalcode VARCHAR(25) UNIQUE,
7 PRIMARY KEY(`officecode`)
8 )ENGINE=
InnoDB DEFAULT CHARSET=utf8mb4;

從MySQL 8.0.17開始,上述程式碼會報錯:

0 row(s) affected, 2 warning(s): 1681 Integer display width is deprecated and will be removed in a future release. 1681 Integer display width is deprecated and will be removed in a future release.

原因為:從MySQL 8.0.17開始,對於整數資料型別,不建議使用display width屬性,即不用M顯示寬度,並且在將來的MySQL版本中將刪除對它的支援。

解決方法:不指定寬度  即INT 後面不要加寬度

程式碼:

CREATE TABLE offices(
officecode INT,
city INT NOT NULL,
address VARCHAR(50),
country VARCHAR(50) NOT NULL,
postalcode VARCHAR(25) UNIQUE,
PRIMARY KEY(`officecode`)
)ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

 例2:在work建立表employees,結構如下:

 

欄位名

資料型別

主鍵

外來鍵

非空

唯一

employeenumber

int(11)

lastname

varchar(50)

firstname

varchar(50)

mobile

varchar(25)

officecode

int(10)

jobtitle

varchar(50)

birth

Datetime

note

varchar(255)

sex

varchar(5)

 

程式碼:

 1 CREATE TABLE employees(
 2 employeenumber INT(11) primary key,
 3 lastname varchar(50) not null,
 4 firstname varchar(50) not null,
 5 mobile varchar(50) unique,
 6 officecode int(10) not null,
 7 jobtitle varchar(50) not null,
 8 birth datetime not null,
 9 note varchar(255),
10 sex varchar(5),
11 constraint fk_off foreign key (officecode) references offices(officecode)
12 )ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;