MySQL入門--基本操作

一、MySQL數據類型

1、正數類型

TINYINT:非常小的整數,類似於

SMALLINT:小整數

MEDIUMINT:中整數

INT,INTEGRE:整數

BIGINT:大整數

使用int數據類型

1)int:

2)int(M):M表示寬度,需要結合另外兩個參數(unsigned,zerofill)進行使用。例如int(5) unsigned zerofill

2、浮點小數

float:4個字節

double:8個字節

使用float與double時

float(M, D), double(M, D):M表示總位數,D表示精度

3、定點小數,底層採用字符串

DECIMAL:

DECIMAL(M, D)

4、日期時間類型

data:表示日期

time:表示時間

datatime:表示日期與時間

year:表示年

timestamp:表示日期和時間。顯示根據毫秒值算出來的本地化的日期時間

5、字符串

mysql沒有單個字符的類型

char:定長字符串 :

​ char(1)/char(20)

varchar:變長字符串

​ varchar(M):最長不超過M個字符

text:長文本,一般用於存儲文字較多且不常被檢索的簡介等信息

6、位類型(瞭解)

​ 二進制表示,BIT(M) 1-64

7、二進制類型

8、枚舉類型

9、集合

二、常用語法

show databases;//查看當前存在的數據庫

show tables;//查看存在的表

use 數據庫名;//使用數據庫

DDL

-- 1、查看當前mysql數據庫管理軟件中都有什麼數據庫
/*
DDL
*/
#註釋
show databases;

#使用一個數據庫
use test;

#創建一個新的數據庫
create databases test;

#創建一個表
use test;
create table t_employee;
#或者 create test.t_employee;

#查看當前數據庫中的表格
show tables;

#告知服務器當前客戶端字符編碼
set names gbk;
#查看某個表的數據
select * from t_employee;
#修改表的數據
update 表名 set 屬性操作;
update t_employee set salary = salary + 1000;

#條件查詢
select * from t_employee where 條件;
select * from t_employee where salary > 2000; 

#修改表的名字
rename table t_employee to new_table;
alter table t_employee rename new_table;

#增加一列
alter table t_employee add tel varchar(11);
#定義新增列的位置
alter table t_employee add tel varchar(11) first;
alter table t_employee add tel varchar(11) after 列名;

#修改列的屬性
alter table t_employee modifiy gender char(2);

#修改列的位置
alter table t_employee modifiy address gender char(2)

DML
-- 1、查看當前mysql數據庫管理軟件中都有什麼數據庫
/*
DDL
*/
#註釋
show databases;

#使用一個數據庫
use test;

#創建一個新的數據庫
create databases test;

#創建一個表
use test;
create table t_employee;
#或者 create test.t_employee;

#查看當前數據庫中的表格
show tables;

#告知服務器當前客戶端字符編碼
set names gbk;
#查看某個表的數據
select * from t_employee;
#修改表的數據
update 表名 set 屬性操作;
update t_employee set salary = salary + 1000;

#條件查詢
select * from t_employee where 條件;
select * from t_employee where salary > 2000; 

#修改表的名字
rename table t_employee to new_table;
alter table t_employee rename new_table;

#增加一列
alter table t_employee add tel varchar(11);
#定義新增列的位置
alter table t_employee add tel varchar(11) first;
alter table t_employee add tel varchar(11) after 列名;

#修改列的屬性
alter table t_employee modifiy gender char(2);

#修改列的位置
alter table t_employee modifiy address gender char(2)

三、約束與索引

3.1、關係型數據庫設計規則

​ 遵循ER模型和三範式

​ E:代表實體,對應數據庫中的一張表

​ R:表示關係

​ 三範式:列不能拆分

​ 唯一標識–數據不能重複,行與行應當能夠區分

​ 關係引用主鍵

3.2、約束與索引的概念

​ 3.2.1、數據完整性是指數據的精確性與可靠性。

​ 數據完整性:

​ 實體完整性-----同一個表中不能存在兩題套完全相同無法區分的記錄

​ 域完整性-------例如年齡範圍,性別範圍

​ 引用完整性----員工所在部門,要在部門表中找到這個部門

​ 用戶自定義完整性–例如用戶名唯一,密碼不能爲空等

​ 3.2.2、約束的分類:

​ 鍵約束:主鍵約束、外鍵約束、唯一鍵約束

​ Not NULL約束:非空約束

​ Check約束:檢查約束

​ Default約束:默認值約束

​ 自增約束

​ 3.2.3、約束與索引

​ 約束是用來對數據業務規則與數據完整性進行實施、維護,約束的作用範圍僅限在當前數據庫,約束可以被當做數據庫對象來處理(邏輯概念,不佔用內存

​ 索引是一個單獨的、物理的存儲在數據頁上的數據結構,是表中一列或者若干列值的集合和對應的只想表中數據值的物理標識的數據頁的邏輯指針清單,索引的存在會增加數據庫的存儲空間,目的是提高查詢速度,但是會增大插入、修改數據的開銷

​ MySQL會在主鍵、唯一鍵、外鍵列上自動創建索引,其他列則需要手動創建

3.3、主鍵約束-primary key

​ 1)唯一且非空

​ 2)一個表只能有一個主鍵約束

​ 3)主鍵約束名就叫做PRIMARY

​ 4)創建主鍵會自動創建相應的索引,同樣刪除主鍵相應的索引也會被刪除

建表前定義主鍵約束
mysql>  create table test02.t_stu(
    ->  sid int primary key,
    ->  sname varchar(20),
    ->  gender char);
Query OK, 0 rows affected (0.03 sec)

mysql> desc t_stu;
+--------+-------------+------+-----+---------+-------+
| Field  | Type        | Null | Key | Default | Extra |
+--------+-------------+------+-----+---------+-------+
| sid    | int(11)     | NO   | PRI | NULL    |       |
| sname  | varchar(20) | YES  |     | NULL    |       |
| gender | char(1)     | YES  |     | NULL    |       |
+--------+-------------+------+-----+---------+-------+
3 rows in set (0.00 sec)

​ 測試主鍵:

mysql>  insert into t_stu values(1, '張三', '男')->  (1, '李四', '女');
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ',
 (1, '李四', '')' at line 1
 
 正確案例:
 mysql>  insert into t_stu values(1, '張三', '男'),(2, '李四', '女');
Query OK, 2 rows affected (0.01 sec)
Records: 2  Duplicates: 0  Warnings: 0

mysql> select * from t_stu;
+-----+-------+--------+
| sid | sname | gender |
+-----+-------+--------+
|   1 | 張三  ||
|   2 | 李四  ||
+-----+-------+--------+
2 rows in set (0.00 sec)
建表後定義主鍵約束
mysql> create table test02.t_stu(
    ->  sid int,
    ->  sname varchar(20),
    ->  gender char);
Query OK, 0 rows affected (0.03 sec)

mysql> desc t_stu;
+--------+-------------+------+-----+---------+-------+
| Field  | Type        | Null | Key | Default | Extra |
+--------+-------------+------+-----+---------+-------+
| sid    | int(11)     | YES  |     | NULL    |       |
| sname  | varchar(20) | YES  |     | NULL    |       |
| gender | char(1)     | YES  |     | NULL    |       |
+--------+-------------+------+-----+---------+-------+
3 rows in set (0.00 sec)

mysql> alter table test02.t_stu add primary key(sid);
Query OK, 0 rows affected (0.05 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> desc t_stu;
+--------+-------------+------+-----+---------+-------+
| Field  | Type        | Null | Key | Default | Extra |
+--------+-------------+------+-----+---------+-------+
| sid    | int(11)     | NO   | PRI | NULL    |       |
| sname  | varchar(20) | YES  |     | NULL    |       |
| gender | char(1)     | YES  |     | NULL    |       |
+--------+-------------+------+-----+---------+-------+
3 rows in set (0.00 sec)

–單列主鍵約束:如上面所述,主鍵只有一個屬性

–複合主鍵約束–兩個或者多個屬性作爲主鍵

mysql>  create table test02.t_course(
    ->  cid int,
    ->  cname varchar(20));
Query OK, 0 rows affected (0.03 sec)
mysql>  create table test02.xuanke(
    ->  cid int,
    ->  sid int,
    ->  score int,
    ->  primary key(sid, cid));
Query OK, 0 rows affected (0.03 sec)

mysql> desc xuanke;
+-------+---------+------+-----+---------+-------+
| Field | Type    | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| cid   | int(11) | NO   | PRI | NULL    |       |
| sid   | int(11) | NO   | PRI | NULL    |       |
| score | int(11) | YES  |     | NULL    |       |
+-------+---------+------+-----+---------+-------+
3 rows in set (0.00 sec)

建表後再確定複合主鍵與上面一樣

刪除主鍵約束
alter table [數據庫名.]表名稱 drop primary key;

mysql> desc t_stu;
+--------+-------------+------+-----+---------+-------+
| Field  | Type        | Null | Key | Default | Extra |
+--------+-------------+------+-----+---------+-------+
| sid    | int(11)     | NO   | PRI | NULL    |       |
| sname  | varchar(20) | YES  |     | NULL    |       |
| gender | char(1)     | YES  |     | NULL    |       |
+--------+-------------+------+-----+---------+-------+
3 rows in set (0.00 sec)

mysql> alter table t_stu drop primary key;
Query OK, 0 rows affected (0.07 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> desc t_stu;
+--------+-------------+------+-----+---------+-------+
| Field  | Type        | Null | Key | Default | Extra |
+--------+-------------+------+-----+---------+-------+
| sid    | int(11)     | NO   |     | NULL    |       |
| sname  | varchar(20) | YES  |     | NULL    |       |
| gender | char(1)     | YES  |     | NULL    |       |
+--------+-------------+------+-----+---------+-------+
3 rows in set (0.00 sec)
3.4、唯一鍵約束

​ 1)一個表可以有多個唯一鍵約束

​ 2)唯一鍵可以爲null

​ 3)唯一鍵的約束名可以自己指定或者默認(如果單列唯一則是列明,如果是多列組合則是第一列的名稱)

​ 4)創建唯一鍵約束也會在對應列上建立索引,刪除唯一鍵約束的方法是通過刪除唯一鍵的索引實現

3.4.1、建立唯一鍵約束

​ 同樣分爲單列唯一鍵與複合唯一鍵

mysql> create table books(
    -> bid int primary key,
    -> bname varchar(20) unique key,
    -> price double);
Query OK, 0 rows affected (0.03 sec)

mysql> desc books;
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| bid   | int(11)     | NO   | PRI | NULL    |       |
| bname | varchar(20) | YES  | UNI | NULL    |       |
| price | double      | YES  |     | NULL    |       |
+-------+-------------+------+-----+---------+-------+
3 rows in set (0.00 sec)

mysql> create table pen(
    -> pid int primary key,
    -> pname varchar(20),
    -> price double,
    -> unique key(pname, price));
Query OK, 0 rows affected (0.03 sec)

mysql> desc pen;
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| pid   | int(11)     | NO   | PRI | NULL    |       |
| pname | varchar(20) | YES  | MUL | NULL    |       |
| price | double      | YES  |     | NULL    |       |
+-------+-------------+------+-----+---------+-------+
3 rows in set (0.00 sec)

建完表後定義唯一鍵

mysql> desc books;
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| bid   | int(11)     | NO   | PRI | NULL    |       |
| bname | varchar(20) | YES  |     | NULL    |       |
| price | double      | YES  |     | NULL    |       |
+-------+-------------+------+-----+---------+-------+
3 rows in set (0.00 sec)

mysql> alter table test02.books add unique key(bname, price);
Query OK, 0 rows affected (0.02 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> desc books;
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| bid   | int(11)     | NO   | PRI | NULL    |       |
| bname | varchar(20) | YES  | MUL | NULL    |       |
| price | double      | YES  |     | NULL    |       |
+-------+-------------+------+-----+---------+-------+
3 rows in set (0.00 sec)
3.4.2、查看索引
mysql> show index from text02.books;
ERROR 1049 (42000): Unknown database 'text02'
mysql> show index from test02.books;
+-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+---------+------------+
| Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment | Visible | Expression |
+-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+---------+------------+
| books |          0 | PRIMARY  |            1 | bid         | A         |           0 |     NULL |   NULL |      | BTREE      |         |               | YES     | NULL       |
| books |          0 | bname    |            1 | bname       | A         |           0 |     NULL |   NULL | YES  | BTREE      |         |               | YES     | NULL       |
| books |          0 | bname    |            2 | price       | A         |           0 |     NULL |   NULL | YES  | BTREE      |         |               | YES     | NULL       |
+-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+---------+------------+
3 rows in set (0.01 sec)

​ 3.4.3、刪除唯一鍵約束–就是刪除索引

mysql> desc books;
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| bid   | int(11)     | NO   | PRI | NULL    |       |
| bname | varchar(20) | YES  | MUL | NULL    |       |
| price | double      | YES  |     | NULL    |       |
+-------+-------------+------+-----+---------+-------+
3 rows in set (0.00 sec)

mysql> alter table books drop index bname;
Query OK, 0 rows affected (0.02 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> desc books;
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| bid   | int(11)     | NO   | PRI | NULL    |       |
| bname | varchar(20) | YES  |     | NULL    |       |
| price | double      | YES  |     | NULL    |       |
+-------+-------------+------+-----+---------+-------+
3 rows in set (0.00 sec)
3.5、非空約束
3.5.1、特點:

​ 1)一個表可以有很多個非空約束

​ 2)非空約束智能針對某一個字段來說

​ 3)非空約束意味着,字段不能存入null值

3.5.2、創建非空約束 (建表時確定)
create table 表名(
字段名 字段屬性 primary key,#主鍵約束
字段名 字段屬性 not null,#非空約束
);
例如:
create table pencil(
	pid int(10) primary key,
	pname varchar(20) unique key not null,
	price double not null);
	mysql> create table pencil(
    -> pid int(10) primary key,
    -> pname varchar(20) unique key not null,
    -> price double not null);
Query OK, 0 rows affected, 1 warning (0.04 sec)

mysql> desc pencil
    -> ;
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| pid   | int(10)     | NO   | PRI | NULL    |       |
| pname | varchar(20) | NO   | UNI | NULL    |       |
| price | double      | NO   |     | NULL    |       |
+-------+-------------+------+-----+---------+-------+
3 rows in set (0.00 sec)

mysql> insert into pencil values(1, 'chenguang', null);
ERROR 1048 (23000): Column 'price' cannot be null
mysql> insert into pencil values(1, 'chenguang', 1.0);
Query OK, 1 row affected (0.01 sec)

mysql> select * from pencil;
+-----+-----------+-------+
| pid | pname     | price |
+-----+-----------+-------+
|   1 | chenguang |     1 |
+-----+-----------+-------+
1 row in set (0.00 sec)
3.5.3、建完表後指定非空約束

alter table 表明 modify 字段名 數據類型 not null;

mysql> desc pencil;
+--------+-------------+------+-----+---------+-------+
| Field  | Type        | Null | Key | Default | Extra |
+--------+-------------+------+-----+---------+-------+
| pid    | int(10)     | NO   | PRI | NULL    |       |
| pname  | varchar(20) | NO   | UNI | NULL    |       |
| price  | double      | NO   |     | NULL    |       |
| number | int(3)      | YES  |     | NULL    |       |
+--------+-------------+------+-----+---------+-------+
4 rows in set (0.00 sec)

mysql> update pencil set number = 5;
Query OK, 1 row affected (0.01 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> alter table pencil modify number int(3) not null;
Query OK, 0 rows affected, 1 warning (0.17 sec)
Records: 0  Duplicates: 0  Warnings: 1

mysql> desc pencil;
+--------+-------------+------+-----+---------+-------+
| Field  | Type        | Null | Key | Default | Extra |
+--------+-------------+------+-----+---------+-------+
| pid    | int(10)     | NO   | PRI | NULL    |       |
| pname  | varchar(20) | NO   | UNI | NULL    |       |
| price  | double      | NO   |     | NULL    |       |
| number | int(3)      | NO   |     | NULL    |       |
+--------+-------------+------+-----+---------+-------+
4 rows in set (0.00 sec)

注意:在設定非空約束時應保證整個表中該屬性非空

3.5.4 刪除非空約束
alter table 表明 modify 字段名 數據類型 not null;

mysql> desc pencil;
+--------+-------------+------+-----+---------+-------+
| Field  | Type        | Null | Key | Default | Extra |
+--------+-------------+------+-----+---------+-------+
| pid    | int(10)     | NO   | PRI | NULL    |       |
| pname  | varchar(20) | NO   | UNI | NULL    |       |
| price  | double      | NO   |     | NULL    |       |
| number | int(3)      | NO   |     | NULL    |       |
+--------+-------------+------+-----+---------+-------+
4 rows in set (0.00 sec)

mysql> alter table pencil modify number int(3);
Query OK, 0 rows affected, 1 warning (0.18 sec)
Records: 0  Duplicates: 0  Warnings: 1

mysql> desc pencil
    -> ;
+--------+-------------+------+-----+---------+-------+
| Field  | Type        | Null | Key | Default | Extra |
+--------+-------------+------+-----+---------+-------+
| pid    | int(10)     | NO   | PRI | NULL    |       |
| pname  | varchar(20) | NO   | UNI | NULL    |       |
| price  | double      | NO   |     | NULL    |       |
| number | int(3)      | YES  |     | NULL    |       |
+--------+-------------+------+-----+---------+-------+
4 rows in set (0.00 sec)
3.6、默認值約束
3.6.1、特點

​ 1)一個表可以有很多個默認值約束

​ 2)智能針對某一個字段

​ 3)意味着該字段沒有進行賦值則會按照默認值進行處理

3.6.2、創建默認值約束
create table 表名(字段 數據類型 約束 default 默認值); 

mysql> desc t_pen;
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| pid   | int(2)      | NO   | PRI | NULL    |       |
| sname | varchar(20) | NO   |     | NULL    |       |
| price | double      | YES  |     | 1       |       |
+-------+-------------+------+-----+---------+-------+
3 rows in set (0.00 sec)

mysql> select * from t_pen;
Empty set (0.00 sec)
mysql> insert into t_pen values(1, '晨光', 3.5);
Query OK, 1 row affected (0.01 sec)

mysql> insert into t_pen values(2, '真彩', default);
Query OK, 1 row affected (0.00 sec)

mysql> select * from t_pen;
+-----+-------+-------+
| pid | sname | price |
+-----+-------+-------+
|   1 | 晨光  |   3.5 |
|   2 | 真彩  |     1 |
+-----+-------+-------+
2 rows in set (0.00 sec)

mysql> insert into t_pen(pid, sname) values(3, '其他');
Query OK, 1 row affected (0.01 sec)

mysql> select * from t_pen;
+-----+-------+-------+
| pid | sname | price |
+-----+-------+-------+
|   1 | 晨光  |   3.5 |
|   2 | 真彩  |     1 |
|   3 | 其他  |     1 |
+-----+-------+-------+
3 rows in set (0.00 sec)
3.6.3、建表後定義默認值
alter table 表名 modify 字段名 數據類型 default 默認值

mysql> desc t_pen;
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| pid   | int(2)      | NO   | PRI | NULL    |       |
| pname | varchar(20) | YES  |     | NULL    |       |
| price | double      | YES  |     | 1       |       |
+-------+-------------+------+-----+---------+-------+
3 rows in set (0.00 sec)
mysql> alter table t_pen change sname pname varchar(20);
Query OK, 0 rows affected (0.17 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> desc t_pen;
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| pid   | int(2)      | NO   | PRI | NULL    |       |
| pname | varchar(20) | YES  |     | NULL    |       |
| price | double      | YES  |     | 1       |       |
+-------+-------------+------+-----+---------+-------+
3 rows in set (0.00 sec)

mysql> insert into t_pen values(5, default, default);
Query OK, 1 row affected (0.01 sec)

mysql> select * from t_pen;
+-----+----------+-------+
| pid | pname    | price |
+-----+----------+-------+
|   1 | 晨光     |   3.5 |
|   2 | 真彩     |     1 |
|   3 | 其他     |     1 |
|   5 | 其它品牌 |     1 |
+-----+----------+-------+
4 rows in set (0.00 sec)
3.7、檢查約束(check)mysql不支持
#檢查約束
 create table t_stu(
 	sid int primary,
 	sname varchar(20),
 	gender char check('男' or '女'));#即只能添加男或者女
3.8、自增約束
3.8.1、特點

​ 1)一個表只能有一個自增約束-因爲一個表只有一個維護自增至的變量

​ 2)自增約束的列只能是整數列

​ 3)自增約束的列必然是鍵列(主鍵、唯一鍵,外鍵)

3.8.2、建表時指定自增約束

​ 自增列:如果指定值,就按照指定的來,如果沒有指定值就自增

​ 如果指定的值是0/null,就按照自增的來.

 create table 表明(
 	字段名 int primary key auto_increment,
 	字段名 數據類型);
 	
mysql>  create table t_stu2(
    ->  sid int primary key auto_increment,
    ->  sname varchar(20));
Query OK, 0 rows affected (0.03 sec)

mysql> desc t_stu2;
+-------+-------------+------+-----+---------+----------------+
| Field | Type        | Null | Key | Default | Extra          |
+-------+-------------+------+-----+---------+----------------+
| sid   | int(11)     | NO   | PRI | NULL    | auto_increment |
| sname | varchar(20) | YES  |     | NULL    |                |
+-------+-------------+------+-----+---------+----------------+
2 rows in set (0.00 sec)

mysql> insert into t_stu2(sname) values('張三');
Query OK, 1 row affected (0.01 sec)

mysql> select * from t_stu2;
+-----+-------+
| sid | sname |
+-----+-------+
|   1 | 張三  |
+-----+-------+
1 row in set (0.00 sec)

mysql> insert into t_stu2(sname) values('李四');
Query OK, 1 row affected (0.01 sec)

mysql> select * from t_stu2;
+-----+-------+
| sid | sname |
+-----+-------+
|   1 | 張三  |
|   2 | 李四  |
+-----+-------+
2 rows in set (0.00 sec)

mysql> insert into t_stu2 values(5, '李四');
Query OK, 1 row affected (0.01 sec)

mysql> select * from t_stu2;
+-----+-------+
| sid | sname |
+-----+-------+
|   1 | 張三  |
|   2 | 李四  |
|   5 | 李四  |
+-----+-------+
3 rows in set (0.00 sec)

mysql> insert into t_stu2(sname) values('wangwu');
Query OK, 1 row affected (0.01 sec)

mysql> select * from t_stu2;
+-----+--------+
| sid | sname  |
+-----+--------+
|   1 | 張三   |
|   2 | 李四   |
|   5 | 李四   |
|   6 | wangwu |
+-----+--------+
4 rows in set (0.00 sec)

alter table 表明 modify 字段名 數據類型 auto_increament;
3.8.3、取消自增
alter table 表明 modify 字段名 數據類型;
3.9、外鍵約束
3.9.1、特點:

​ 1)一個表可以有很多個外鍵約束

​ 2)外鍵約束是需要一個表的兩個字段或者兩個表的兩個字段之間建立外鍵約束

​ 3)外鍵約束一定是在從表/子表中建立

​ 主表、子表:參考別人的,以來別人的

​ 從表、父表:被參考的,被依賴的

​ 4)在從表中外鍵約束的列,與在主表中外鍵約束參考的列,這兩個列名稱可以不一樣,但是意義、數據類型必須一致

​ 5)外鍵約束是約束雙方行爲的

​ 對於主表來說:修改與刪除受限制

​ 對於從表來說:添加與修改被限制

​ 6)主表被參考的列必須爲主鍵列

​ 舉例:部門表與員工表,員工的部門必須在部門表中有體現,那麼部門表修改與刪除的部門不能存在於員工表中,員工表修改與添加的部門必須在部門表中

建表時先建立主表,再建立從表

刪表時先刪除從表,再刪除主表

3.9.2、約束等級(5個)

​ 1)Cascade方式:級聯

​ 主動權在主表上,如果主表被依賴字段修改了,從表對應的外鍵字段跟着修改

​ 2)Set null方式

​ 主動權在主表上,如果主表被依賴字段修改或者刪除了,那麼修改爲null

​ 3)No action方式:不作爲模式

​ 4)Restrict方式:嚴格

​ 如果主表的被依賴字段的值被引用了,那麼主表對該字段的修改和刪除就被限制了

​ 5)set default方式:mysql 的Innodb引擎不支持

3.9.3、在建表時指定外鍵
mysql> create database 0513db;
Query OK, 1 row affected (0.01 sec)

mysql> use 0513db;
Database changed
mysql> #主表
mysql> create table dept(
    -> did int primary key,
    -> dname varchar(20));
Query OK, 0 rows affected (0.03 sec)

mysql> #從表
mysql> create table emp(
    -> eid int primary key,
    -> ename varchar(20),
    -> did int,
    -> foreign key(did) references dept(did) on update cascade on delete set null);
Query OK, 0 rows affected (0.03 sec)

mysql> desc dept;
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| did   | int(11)     | NO   | PRI | NULL    |       |
| dname | varchar(20) | YES  |     | NULL    |       |
+-------+-------------+------+-----+---------+-------+
2 rows in set (0.00 sec)

mysql> desc emp;
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| eid   | int(11)     | NO   | PRI | NULL    |       |
| ename | varchar(20) | YES  |     | NULL    |       |
| did   | int(11)     | YES  | MUL | NULL    |       |
+-------+-------------+------+-----+---------+-------+
3 rows in set (0.00 sec)

mysql> insert into dept values(1, '諮詢部'),
    -> (2, '外聯部');
    
    mysql> select * from dept;
+-----+--------+
| did | dname  |
+-----+--------+
|   1 | 諮詢部 |
|   2 | 生產部 |
+-----+--------+
2 rows in set (0.00 sec)

insert into emp values(2, '李四', 1);
Query OK, 1 row affected (0.01 sec)
mysql> select * from emp;
+-----+-------+------+
| eid | ename | did  |
+-----+-------+------+
|   1 | 張三  |    1 |
|   2 | 李四  |    1 |
+-----+-------+------+
2 rows in set (0.00 sec)

mysql> insert into emp values(3, '王五', 3);
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`0513db`.`emp`, CONSTRAINT `emp_ibfk_1` FOREIGN KEY (`did`) REFERENCES `dept` (`did`) ON DELETE SET NULL ON UPDATE CASCADE)

mysql> delete from emp where did = 1;
Query OK, 2 rows affected (0.01 sec)

#刪除從表中的數據
mysql> select * from emp;
+-----+-------+------+
| eid | ename | did  |
+-----+-------+------+
|   3 | 王五  |    2 |
+-----+-------+------+
1 row in set (0.00 sec) 

#級聯約束,修改主表元素,從表也改變
mysql> select * from emp;
+-----+-------+------+
| eid | ename | did  |
+-----+-------+------+
|   3 | 王五  |    2 |
+-----+-------+------+
1 row in set (0.00 sec)

mysql> update dept set did = 5 where did = 2;
Query OK, 1 row affected (0.01 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> select * from emp;;
+-----+-------+------+
| eid | ename | did  |
+-----+-------+------+
|   3 | 王五  |    5 |
+-----+-------+------+
1 row in set (0.00 sec)
3.9.4、建表後指定外鍵
alter table 從表名稱 add foreign key(從表字段) references 主表名(主表字段) on update cascade on delete set null);
3.9.5、刪除外鍵
alter table 從表名稱 drop foreign key 約束名;
#約束名是隨機生成的,記錄在 information_schema中
#查看約束的指令爲:
select * from  information_schema.table_constraints where table_name = '表名稱'

mysql> select * from information_schema.table_constraints where table_name = 'emp';
+--------------------+-------------------+-----------------+--------------+------------+-----------------+----------+
| CONSTRAINT_CATALOG | CONSTRAINT_SCHEMA | CONSTRAINT_NAME | TABLE_SCHEMA | TABLE_NAME | CONSTRAINT_TYPE | ENFORCED |
+--------------------+-------------------+-----------------+--------------+------------+-----------------+----------+
| def                | 0513db            | PRIMARY         | 0513db       | emp        | PRIMARY KEY     | YES      |
| def                | 0513db            | emp_ibfk_1      | 0513db       | emp        | FOREIGN KEY     | YES      |
+--------------------+-------------------+-----------------+--------------+------------+-----------------+----------+
2 rows in set (0.01 sec)

#刪除操作
mysql> alter table emp drop foreign key emp_ibfk_1;
Query OK, 0 rows affected (0.01 sec)
Records: 0  Duplicates: 0  Warnings: 0
mysql> select * from information_schema.table_constraints where table_name = 'emp';
+--------------------+-------------------+-----------------+--------------+------------+-----------------+----------+
| CONSTRAINT_CATALOG | CONSTRAINT_SCHEMA | CONSTRAINT_NAME | TABLE_SCHEMA | TABLE_NAME | CONSTRAINT_TYPE | ENFORCED |
+--------------------+-------------------+-----------------+--------------+------------+-----------------+----------+
| def                | 0513db            | PRIMARY         | 0513db       | emp        | PRIMARY KEY     | YES      |
+--------------------+-------------------+-----------------+--------------+------------+-----------------+----------+
1 row in set (0.00 sec)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章