MySQL表操做

1、表介紹

表就至關於文件,表中的一條記錄就至關於文件的一行內容,不一樣的是,表中的一條記錄有對應的標題,稱爲表的字段python

還記得咱們以前寫過的‘員工信息表做業’麼?存儲這員工信息的文件是這樣的:mysql

id,name,age,sex,phone,job
1,Tank,83,female,13651054608,IT
2,Nick,26,male,13304320533,Tearcher
3,Sean,25,male,13332353222,IT
4,Jason,40,male,13332353333,IT

若是把上面這個文件改爲一張表,應該是下面這個樣子sql

id name age sex phone job
1 Tank 83 female 13651054608 IT
2 Nick 26 male 13304320533 Tearcher
3 Sean 25 male 13332353222 IT
4 Jason 40 male 13332353333 IT

id,name,age,sex,phone,job稱爲字段,其他的,一行內容稱爲一條記錄。spa

2、建立表

2.1 語法

create table 表名( 字段名1 類型[(寬度) 約束條件], 字段名2 類型[(寬度) 約束條件], 字段名3 類型[(寬度) 約束條件] );設計

注意:code

  1. 在同一張表中,字段名是不能相同
  2. 寬度和約束條件可選
  3. 字段名和類型是必須的

2.2 建表

mysql> create database staff;
Query OK, 1 row affected (0.00 sec)

mysql> use staff;
Database changed
mysql> create table staff_info (id int,name varchar(50),age int(3),sex enum('male','female'),phone bigint(11),job varchar(11));
Query OK, 0 rows affected (0.02 sec)


mysql> show tables;
+-----------------+
| Tables_in_staff |
+-----------------+
| staff_info      |
+-----------------+
row in set (0.00 sec)

mysql> desc staff_info;
+-------+-----------------------+------+-----+---------+-------+
| Field | Type                  | Null | Key | Default | Extra |
+-------+-----------------------+------+-----+---------+-------+
| id    | int(11)               | YES  |     | NULL    |       |
| name  | varchar(50)           | YES  |     | NULL    |       |
| age   | int(3)                | YES  |     | NULL    |       |
| sex   | enum('male','female') | YES  |     | NULL    |       |
| phone | bigint(11)            | YES  |     | NULL    |       |
| job   | varchar(11)           | YES  |     | NULL    |       |
+-------+-----------------------+------+-----+---------+-------+
rows in set (0.00 sec)

mysql> select id,name,sex from staff_info;
Empty set (0.00 sec)

mysql> select * from staff_info;
Empty set (0.00 sec)

2.3 插入數據

mysql> insert into staff_info (id,name,age,sex,phone,job) values (1,'Tank',83,'female',13651054608,'IT');
Query OK, 1 row affected (0.00 sec)

mysql> insert into staff_info values (2,'Nick',26,'male',13304320533,'Teacher');
Query OK, 1 row affected (0.00 sec)

mysql> insert into staff_info values (3,'Sean',25,'male',13332353222,'IT'),(4,'Jason',40,'male',13332353333,'IT');
Query OK, 2 rows affected (0.00 sec)
Records: 2  Duplicates: 0  Warnings: 0

mysql> select * from staff_info;
+------+----------+------+--------+-------------+---------+
| id   | name     | age  | sex    | phone       | job     |
+------+----------+------+--------+-------------+---------+
|    1 | Tank     |   83 | female | 13651054608 | IT      |
|    2 | Nick     |   26 | male   | 13304320533 | Teacher |
|    3 | Sean    |   25 | male   | 13332353222 | IT      |
|    4 | Jason |   40 | male   | 13332353333 | IT      |
+------+----------+------+--------+-------------+---------+
rows in set (0.00 sec)

3、查看錶結構

查看錶結構有兩種方式:htm

describe [tablename];這種方法和desc [tablename];效果相同;能夠查看當前的表結構blog

雖然desc命令能夠查看錶的定義,可是其輸出的信息還不夠全面,爲了獲得更全面的表定義信息,有時候就須要查看建立表的SQL語句,使用show create table語法。除了能夠看到表定義以外,還能夠看到engine(存儲引擎)和charset(字符集)等信息。(\G選項的含義是是的記錄可以豎向排列,以便更好的顯示內容較長的記錄。)ci

3.1 desc和show create table

mysql> describe staff_info;
+-------+-----------------------+------+-----+---------+-------+
| Field | Type                  | Null | Key | Default | Extra |
+-------+-----------------------+------+-----+---------+-------+
| id    | int(11)               | YES  |     | NULL    |       |
| name  | varchar(50)           | YES  |     | NULL    |       |
| age   | int(3)                | YES  |     | NULL    |       |
| sex   | enum('male','female') | YES  |     | NULL    |       |
| phone | bigint(11)            | YES  |     | NULL    |       |
| job   | varchar(11)           | YES  |     | NULL    |       |
+-------+-----------------------+------+-----+---------+-------+
rows in set (0.00 sec)

mysql> desc staff_info;
+-------+-----------------------+------+-----+---------+-------+
| Field | Type                  | Null | Key | Default | Extra |
+-------+-----------------------+------+-----+---------+-------+
| id    | int(11)               | YES  |     | NULL    |       |
| name  | varchar(50)           | YES  |     | NULL    |       |
| age   | int(3)                | YES  |     | NULL    |       |
| sex   | enum('male','female') | YES  |     | NULL    |       |
| phone | bigint(11)            | YES  |     | NULL    |       |
| job   | varchar(11)           | YES  |     | NULL    |       |
+-------+-----------------------+------+-----+---------+-------+
rows in set (0.00 sec)

mysql> show create table staff_info\G;
*************************** 1. row ***************************
       Table: staff_info
Create Table: CREATE TABLE `staff_info` (
  `id` int(11) DEFAULT NULL,
  `name` varchar(50) DEFAULT NULL,
  `age` int(3) DEFAULT NULL,
  `sex` enum('male','female') DEFAULT NULL,
  `phone` bigint(11) DEFAULT NULL,
  `job` varchar(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8
row in set (0.01 sec)

ERROR: 
No query specified

4、MySQL支持的數據類型

MySQL支持的數據類型:http://www.javashuo.com/article/p-snrjzypl-bb.html

5、MySQL表的完整性約束

MySQL表的完整性約束:http://www.javashuo.com/article/p-ppqbmnto-bd.html

6、修改表結構

語法:
1. 修改表名
      ALTER TABLE 表名 
                      RENAME 新表名;

2. 增長字段
      ALTER TABLE 表名
                      ADD 字段名  數據類型 [完整性約束條件…],
                      ADD 字段名  數據類型 [完整性約束條件…];
                            
3. 刪除字段
      ALTER TABLE 表名 
                      DROP 字段名;

4. 修改字段
      ALTER TABLE 表名 
                      MODIFY  字段名 數據類型 [完整性約束條件…];
      ALTER TABLE 表名 
                      CHANGE 舊字段名 新字段名 舊數據類型 [完整性約束條件…];
      ALTER TABLE 表名 
                      CHANGE 舊字段名 新字段名 新數據類型 [完整性約束條件…];

5.修改字段排列順序/在增長的時候指定字段位置
    ALTER TABLE 表名
                     ADD 字段名  數據類型 [完整性約束條件…]  FIRST;
    ALTER TABLE 表名
                     ADD 字段名  數據類型 [完整性約束條件…]  AFTER 字段名;
    ALTER TABLE 表名
                     CHANGE 字段名  舊字段名 新字段名 新數據類型 [完整性約束條件…]  FIRST;
    ALTER TABLE 表名
                     MODIFY 字段名  數據類型 [完整性約束條件…]  AFTER 字段名;

6.1 alter操做非空和惟一(瞭解)

create table t(id int unique,name char(10) not null);

#去掉null約束
alter table t modify name char(10) null;
# 添加null約束
alter table t modify name char(10) not null;


# 去掉unique約束
alter table t drop index id;
# 添加unique約束
alter table t modify id int unique;

alter處理null和unique約束

6.2 alter操做主鍵(瞭解)

一、首先建立一個數據表table_test:
create table table_test(
`id` varchar(100) NOT NULL,
`name` varchar(100) NOT NULL,
PRIMARY KEY (`name`)
); 
二、若是發現主鍵設置錯了,應該是id是主鍵,但現在表裏已經有好多數據了,不能刪除表再重建了,僅僅能在這基礎上改動表結構。
先刪除主鍵
alter table table_test drop primary key;
而後再增長主鍵
alter table table_test add primary key(id);
注:在增長主鍵以前,必須先把反覆的id刪除掉。

6.3 爲表添加外鍵(瞭解)

建立press表
CREATE TABLE `press` (
  `id` int(11) NOT NULL,
  `name` char(10) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ;

建立book表
CREATE TABLE `book` (
  `id` int(11) DEFAULT NULL,
  `bk_name` char(12) DEFAULT NULL,
  `press_id` int(11) NOT NULL,
  KEY `press_id` (`press_id`)
) ;

爲book表添加外鍵
alter table book add constraint fk_id foreign key(press_id) references press(id);

刪除外鍵
alter table book drop foreign key fk_id;

6.4 示例

mysql> desc staff_info;
+-------+-----------------------+------+-----+---------+-------+
| Field | Type                  | Null | Key | Default | Extra |
+-------+-----------------------+------+-----+---------+-------+
| id    | int(11)               | YES  |     | NULL    |       |
| name  | varchar(50)           | YES  |     | NULL    |       |
| age   | int(3)                | YES  |     | NULL    |       |
| sex   | enum('male','female') | YES  |     | NULL    |       |
| phone | bigint(11)            | YES  |     | NULL    |       |
| job   | varchar(11)           | YES  |     | NULL    |       |
+-------+-----------------------+------+-----+---------+-------+
rows in set (0.00 sec)

# 表重命名
mysql> alter table staff_info rename staff;
Query OK, 0 rows affected (0.00 sec)

mysql> desc staff;
+-------+-----------------------+------+-----+---------+-------+
| Field | Type                  | Null | Key | Default | Extra |
+-------+-----------------------+------+-----+---------+-------+
| id    | int(11)               | YES  |     | NULL    |       |
| name  | varchar(50)           | YES  |     | NULL    |       |
| age   | int(3)                | YES  |     | NULL    |       |
| sex   | enum('male','female') | YES  |     | NULL    |       |
| phone | bigint(11)            | YES  |     | NULL    |       |
| job   | varchar(11)           | YES  |     | NULL    |       |
+-------+-----------------------+------+-----+---------+-------+
rows in set (0.00 sec)

# 刪除sex列
mysql> alter table staff drop sex;
Query OK, 0 rows affected (0.02 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> desc staff;
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| id    | int(11)     | YES  |     | NULL    |       |
| name  | varchar(50) | YES  |     | NULL    |       |
| age   | int(3)      | YES  |     | NULL    |       |
| phone | bigint(11)  | YES  |     | NULL    |       |
| job   | varchar(11) | YES  |     | NULL    |       |
+-------+-------------+------+-----+---------+-------+
rows in set (0.01 sec)

# 添加列
mysql> alter table staff add sex enum('male','female');
Query OK, 0 rows affected (0.03 sec)
Records: 0  Duplicates: 0  Warnings: 0

# 修改id的寬度
mysql> alter table staff modify id int(4);
Query OK, 0 rows affected (0.02 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> desc staff;
+-------+-----------------------+------+-----+---------+-------+
| Field | Type                  | Null | Key | Default | Extra |
+-------+-----------------------+------+-----+---------+-------+
| id    | int(4)                | YES  |     | NULL    |       |
| name  | varchar(50)           | YES  |     | NULL    |       |
| age   | int(3)                | YES  |     | NULL    |       |
| phone | bigint(11)            | YES  |     | NULL    |       |
| job   | varchar(11)           | YES  |     | NULL    |       |
| sex   | enum('male','female') | YES  |     | NULL    |       |
+-------+-----------------------+------+-----+---------+-------+
rows in set (0.01 sec)

# 修改name列的字段名
mysql> alter table staff change name sname varchar(20);
Query OK, 4 rows affected (0.03 sec)
Records: 4  Duplicates: 0  Warnings: 0

mysql> desc staff;
+-------+-----------------------+------+-----+---------+-------+
| Field | Type                  | Null | Key | Default | Extra |
+-------+-----------------------+------+-----+---------+-------+
| id    | int(4)                | YES  |     | NULL    |       |
| sname | varchar(20)           | YES  |     | NULL    |       |
| age   | int(3)                | YES  |     | NULL    |       |
| phone | bigint(11)            | YES  |     | NULL    |       |
| job   | varchar(11)           | YES  |     | NULL    |       |
| sex   | enum('male','female') | YES  |     | NULL    |       |
+-------+-----------------------+------+-----+---------+-------+
rows in set (0.00 sec)

# 修改sex列的位置
mysql> alter table staff modify sex enum('male','female') after sname;
Query OK, 0 rows affected (0.02 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> desc staff;
+-------+-----------------------+------+-----+---------+-------+
| Field | Type                  | Null | Key | Default | Extra |
+-------+-----------------------+------+-----+---------+-------+
| id    | int(4)                | YES  |     | NULL    |       |
| sname | varchar(20)           | YES  |     | NULL    |       |
| sex   | enum('male','female') | YES  |     | NULL    |       |
| age   | int(3)                | YES  |     | NULL    |       |
| phone | bigint(11)            | YES  |     | NULL    |       |
| job   | varchar(11)           | YES  |     | NULL    |       |
+-------+-----------------------+------+-----+---------+-------+
rows in set (0.00 sec)

# 建立自增id主鍵
mysql> alter table staff modify id int(4) primary key auto_increment;
Query OK, 4 rows affected (0.02 sec)
Records: 4  Duplicates: 0  Warnings: 0

mysql> desc staff;
+-------+-----------------------+------+-----+---------+----------------+
| Field | Type                  | Null | Key | Default | Extra          |
+-------+-----------------------+------+-----+---------+----------------+
| id    | int(4)                | NO   | PRI | NULL    | auto_increment |
| sname | varchar(20)           | YES  |     | NULL    |                |
| sex   | enum('male','female') | YES  |     | NULL    |                |
| age   | int(3)                | YES  |     | NULL    |                |
| phone | bigint(11)            | YES  |     | NULL    |                |
| job   | varchar(11)           | YES  |     | NULL    |                |
+-------+-----------------------+------+-----+---------+----------------+
rows in set (0.00 sec)

# 刪除主鍵,能夠看到刪除一個自增主鍵會報錯
mysql> alter table staff drop primary key;
ERROR 1075 (42000): Incorrect table definition; there can be only one auto column and it must be defined as a key

# 須要先去掉主鍵的自增約束,而後再刪除主鍵約束
mysql> alter table staff modify id int(11);
Query OK, 4 rows affected (0.02 sec)
Records: 4  Duplicates: 0  Warnings: 0

mysql> desc staff;
+-------+-----------------------+------+-----+---------+-------+
| Field | Type                  | Null | Key | Default | Extra |
+-------+-----------------------+------+-----+---------+-------+
| id    | int(11)               | NO   | PRI | 0       |       |
| sname | varchar(20)           | YES  |     | NULL    |       |
| sex   | enum('male','female') | YES  |     | NULL    |       |
| age   | int(3)                | YES  |     | NULL    |       |
| phone | bigint(11)            | YES  |     | NULL    |       |
| job   | varchar(11)           | YES  |     | NULL    |       |
+-------+-----------------------+------+-----+---------+-------+
rows in set (0.01 sec)

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

# 添加聯合主鍵
mysql> alter table staff add primary key (sname,age);
Query OK, 0 rows affected (0.02 sec)
Records: 0  Duplicates: 0  Warnings: 0

# 刪除主鍵
mysql> alter table staff drop primary key;
Query OK, 4 rows affected (0.02 sec)
Records: 4  Duplicates: 0  Warnings: 0

# 建立主鍵id
mysql> alter table staff add primary key (id);
Query OK, 0 rows affected (0.02 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> desc staff;
+-------+-----------------------+------+-----+---------+-------+
| Field | Type                  | Null | Key | Default | Extra |
+-------+-----------------------+------+-----+---------+-------+
| id    | int(11)               | NO   | PRI | 0       |       |
| sname | varchar(20)           | NO   |     |         |       |
| sex   | enum('male','female') | YES  |     | NULL    |       |
| age   | int(3)                | NO   |     | 0       |       |
| phone | bigint(11)            | YES  |     | NULL    |       |
| job   | varchar(11)           | YES  |     | NULL    |       |
+-------+-----------------------+------+-----+---------+-------+
rows in set (0.00 sec)

# 爲主鍵添加自增屬性
mysql> alter table staff modify id int(4) auto_increment;
Query OK, 4 rows affected (0.02 sec)
Records: 4  Duplicates: 0  Warnings: 0

mysql> desc staff;
+-------+-----------------------+------+-----+---------+----------------+
| Field | Type                  | Null | Key | Default | Extra          |
+-------+-----------------------+------+-----+---------+----------------+
| id    | int(4)                | NO   | PRI | NULL    | auto_increment |
| sname | varchar(20)           | NO   |     |         |                |
| sex   | enum('male','female') | YES  |     | NULL    |                |
| age   | int(3)                | NO   |     | 0       |                |
| phone | bigint(11)            | YES  |     | NULL    |                |
| job   | varchar(11)           | YES  |     | NULL    |                |
+-------+-----------------------+------+-----+---------+----------------+
rows in set (0.00 sec)

7、刪除表

DROP TABLE 表名;

8、多表結構的分析和建立

8.1 如何找出兩張表之間的關係

分析步驟:

  1. 先站在左表的角度去找:是否左表的多條記錄能夠對應右表的一條記錄,若是是,則證實左表的一個字段foreign key 右表一個字段(一般是id)

  2. 再站在右表的角度去找:是否右表的多條記錄能夠對應左表的一條記錄,若是是,則證實右表的一個字段foreign key 左表一個字段(一般是id)

  3. 總結:
    1. 多對一:
      • 若是隻有步驟1成立,則是左表多對一右表
      • 若是隻有步驟2成立,則是右表多對一左表
    2. 多對多
      • 若是步驟1和2同時成立,則證實這兩張表時一個雙向的多對一,即多對多,須要定義一個這兩張表的關係表來專門存放兩者的關係
    3. 一對一:
      • 若是1和2都不成立,而是左表的一條記錄惟一對應右表的一條記錄,反之亦然。這種狀況很簡單,就是在左表foreign key右表的基礎上,將左表的外鍵字段設置成unique便可

8.2 創建表之間的關係——一對多

一對多或稱爲多對一

三張表:出版社,做者信息,書

一對多(或多對一):一個出版社能夠出版多本書

關聯方式:foreign key

8.2.1 sql示例

=====================多對一=====================
create table press(
id int primary key auto_increment,
name varchar(20)
);

create table book(
id int primary key auto_increment,
name varchar(20),
press_id int not null,
foreign key(press_id) references press(id)
on delete cascade
on update cascade
);


insert into press(name) values
('北京工業地雷出版社'),
('人民音樂很差聽出版社'),
('知識產權沒有用出版社')
;

insert into book(name,press_id) values
('九陽神功',1),
('九陰真經',2),
('九陰白骨爪',2),
('獨孤九劍',3),
('降龍十巴掌',2),
('葵花寶典',3)
;

8.2.2 其餘示例

班級和學生:一個班級能夠對應多個學生,但一個學生只能對應一個班級

主機和機房:一個機房能夠有多臺主機,可是一個主機只能屬於一個機房

8.3 創建表之間的關係——多對多

三張表:出版社,做者信息,書

多對多:一個做者能夠寫多本書,一本書也能夠有多個做者,雙向的一對多,即多對多
  
關聯方式:foreign key+一張新的表

8.3.1 sql示例

=====================多對多=====================
create table author(
id int primary key auto_increment,
name varchar(20)
);


#這張表就存放做者表與書表的關係,即查詢兩者的關係查這表就能夠了
create table author2book(
id int not null unique auto_increment,
author_id int not null,
book_id int not null,
constraint fk_author foreign key(author_id) references author(id)
on delete cascade
on update cascade,
constraint fk_book foreign key(book_id) references book(id)
on delete cascade
on update cascade,
primary key(author_id,book_id)
);


#插入四個做者,id依次排開
insert into author(name) values('Nick'),('Tank'),('Oscar'),('Mac');

#每一個做者與本身的表明做以下
Nick: 
九陽神功
九陰真經
九陰白骨爪
獨孤九劍
降龍十巴掌
葵花寶典
Tank: 
九陽神功
葵花寶典
Oscar:
獨孤九劍
降龍十巴掌
葵花寶典
Mac:
九陽神功


insert into author2book(author_id,book_id) values
(1,1),
(1,2),
(1,3),
(1,4),
(1,5),
(1,6),
(2,1),
(2,6),
(3,4),
(3,5),
(3,6),
(4,1)
;

8.3.2 其餘示例

服務和機器:一個服務可能被部署到多臺機器上,一臺機器上也能夠部署多個服務

學生和課程:一個學生能夠選擇多門課程,一門課程也能夠被多個學生選擇

8.4 創建表之間的關係——一對一

兩張表:學生表和客戶表

一對一:一個學生是一個客戶

關聯方式:foreign key+unique

8.4.1 sql示例

create table customer(
    -> id int primary key auto_increment,
    -> name varchar(20) not null,
    -> qq varchar(10) not null,
    -> phone char(16) not null
    -> );

create table student(
    -> id int primary key auto_increment,
    -> class_name varchar(20) not null,
    -> customer_id int unique, #該字段必定要是惟一的
    -> foreign key(customer_id) references customer(id) #外鍵的字段必定要保證unique
    -> on delete cascade
    -> on update cascade
    -> );

#增長客戶
mysql> insert into customer(name,qq,phone) values
    -> ('韓蕾','31811231',13811341220),
    -> ('楊瀾','123123123',15213146809),
    -> ('翁惠天','283818181',1867141331),
    -> ('楊宗河','283818181',1851143312),
    -> ('袁承明','888818181',1861243314),
    -> ('袁清','112312312',18811431230)

mysql> #增長學生
mysql> insert into student(class_name,customer_id) values
    -> ('脫產1班',3),
    -> ('週末1期',4),
    -> ('週末1期',5)
    -> ;

8.4.2 其餘示例

例一:一個用戶只有一個博客

例二:一個管理員惟一對應一個用戶

9、做業

根據表結構合理設計表與表之間的主外鍵關係和約束,並完成表結構的建立。

197-MySQL表操做-01.png?x-oss-process=style/watermark

相關文章
相關標籤/搜索