咱們在編寫任何程序以前,都須要事先寫好基於網絡操做一臺主機上文件的程序(socket服務端與客戶端程序),因而有人將此類程序寫成一個 專門的處理軟件,這就是mysql等數據庫管理軟件的由來,但mysql解決的不只僅是數據共享的問題,還有查詢效率,安全性等一系列問題, 總之,把程序員從數據管理中解脫出來,專一於本身的程序邏輯的編寫。
數據(Data):描述事物的符號記錄稱爲數據,描述事物的符號既能夠是數字,也能夠是文字、圖片,圖像、聲音、語言等,數據由多種表現形式,它們均可以通過數字化後存入計算機;在計算機中描述一個事物,就須要抽取這一事物的典型特徵,組成一條記錄,就至關於文件裏的一行內容。html
數據庫(Databases,簡稱DB):數據庫庫即存放數據的倉庫,只不過這個倉庫是在計算機存儲設備上,並且數據是按必定的格式存放的;數據庫是長期存放在計算機內、有組織、可共享的數據便可。數據庫中的數據按必定的數據模型組織、描述和儲存,具備較小的冗餘度、較高的數據獨立性和易擴展性,並可爲各類 用戶共享。python
數據庫管理系統(DataBase Management System 簡稱DBMS)在瞭解了Data與DB的概念後,如何科學地組織和存儲數據,如何高效獲取和維護數據成了關鍵mysql
這就用到了一個系統軟件---數據庫管理系統如MySQL、Oracle、SQLite、Access、MS SQL Server程序員
常見的數據庫模型分爲關係型數據庫(MySQL、Oracle、SQL Server....)和非關係型數據庫(文檔存儲數據庫MongoDB;鍵值存儲數據庫Redis、Memcached、列存儲數據庫HBase、圖形數據庫Neo4J)redis
mysql主要用於大型門戶,例如搜狗、新浪等,它主要的優點就是開放源代碼,由於開放源代碼這個數據庫是免費的,他如今是甲骨文公司的產品。
oracle主要用於銀行、鐵路、飛機場等。該數據庫功能強大,軟件費用高。也是甲骨文公司的產品。
sql server是微軟公司的產品,主要應用於大中型企業,如聯想、方正等。sql
數據庫服務器-:運行數據庫管理軟件 數據庫管理軟件:管理-數據庫 數據庫:即文件夾,用來組織文件/表 表:即文件,用來存放多行內容/多條記錄
mysql就是一個基於socket編寫的C/S架構的軟件
客戶端軟件
mysql自帶:如mysql命令,mysqldump命令等
python模塊:如pymysql
數據庫管理軟件分類--->>>
分兩大類:
關係型:如sqllite,db2,oracle,access,sql server,MySQL,注意:sql語句通用
非關係型:mongodb,redis,memcache
能夠簡單的理解爲:
關係型數據庫須要有表結構
非關係型數據庫是key-value存儲的,沒有表結構
mysql windows7的安裝:https://jingyan.baidu.com/article/f3ad7d0ffc061a09c3345bf0.html?qq-pf-to=pcqq.c2cmongodb
關於如何清除mysql,很很差清除,一系列的註冊表什麼的:參考 https://blog.csdn.net/renwudao24/article/details/51860752數據庫
存儲數據的倉庫windows
mysql就是套接字服務端、客戶端而已;安全
win+R 輸入servers.msc 找到服務裏邊去啓動mysql
select user(); #查看當前登陸的帳號 mysql> select user(); +----------------+ | user() | +----------------+ | ODBC@localhost | #表明本地帳號 +----------------+ 1 row in set (0.10 sec)
C:\Users\Administrator>mysql -uroot -p #uroot就是管理員帳號 Enter password: Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 9 .... mysql> select user(); +----------------+ | user() | +----------------+ | root@localhost | +----------------+ 1 row in set (0.00 sec)
C:\Users\Administrator>mysqladmin -uroot -p password '123' #修改默認密碼 Enter password: Warning: Using a password on the command line interface can be insecure. Warning: single quotes were not trimmed from the password by your command line client, as you might have expected.
C:\Windows\System32>tasklist | findstr mysql mysqld.exe 2032 Services 0 5,324 K C:\Windows\System32>taskkill /F /PID 2032 成功: 已終止 PID 爲 2032 的進程。 C:\Windows\System32>net start MySQL MySQL 服務正在啓動 .. MySQL 服務已經啓動成功。
統一字符編碼
關於win7修改默認字符編碼:https://blog.csdn.net/u013474104/article/details/52486880
建個my.ini配置文件
# For advice on how to change settings please see # http://dev.mysql.com/doc/refman/5.6/en/server-configuration-defaults.html # *** DO NOT EDIT THIS FILE. It's a template which will be copied to the # *** default location during install, and will be replaced if you # *** upgrade to a newer version of MySQL. [mysqld] character-set-server=utf8 collation-server=utf8_general_ci # Remove leading # and set to the amount of RAM for the most important data # cache in MySQL. Start at 70% of total RAM for dedicated server, else 10%. # innodb_buffer_pool_size = 128M # Remove leading # to turn on a very important data integrity option: logging # changes to the binary log between backups. # log_bin # These are commonly set, remove the # and set as required. basedir = C:\mysql-5.6.39-winx64 #這兩個須要自行修改配置下path datadir = C:\mysql-5.6.39-winx64\data # port = ..... # server_id = ..... # Remove leading # to set options mainly useful for reporting servers. # The server defaults are faster for transactions and fast SELECTs. # Adjust sizes as needed, experiment to find the optimal values. # join_buffer_size = 128M # sort_buffer_size = 2M # read_rnd_buffer_size = 2M sql_mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES [mysql] default-character-set = utf8 [mysql.server] default-character-set = utf8 [mysqld_safe] default-character-set = utf8 [client] default-character-set = utf8
C:\Windows\system32>mysql Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 1 Server version: 5.6.39 MySQL Community Server (GPL) Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved. Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners. Type 'help;' or '\h' for help. Type '\c' to clear the current input statement. mysql> \s -------------- mysql Ver 14.14 Distrib 5.6.39, for Win64 (x86_64) Connection id: 1 Current database: Current user: ODBC@localhost SSL: Not in use Using delimiter: ; Server version: 5.6.39 MySQL Community Server (GPL) Protocol version: 10 Connection: localhost via TCP/IP Server characterset: latin1 Db characterset: latin1 Client characterset: gbk Conn. characterset: gbk TCP port: 3306 Uptime: 18 sec Threads: 1 Questions: 5 Slow queries: 0 Opens: 67 Flush tables: 1 Open tabl es: 60 Queries per second avg: 0.277 -------------- mysql> show variables like 'character%'; +--------------------------+----------------------------------------+ | Variable_name | Value | +--------------------------+----------------------------------------+ | character_set_client | gbk | | character_set_connection | gbk | | character_set_database | latin1 | | character_set_filesystem | binary | | character_set_results | gbk | | character_set_server | latin1 | | character_set_system | utf8 | | character_sets_dir | C:\mysql-5.6.39-winx64\share\charsets\ | +--------------------------+----------------------------------------+ 8 rows in set (0.00 sec) mysql> exit Bye C:\Windows\system32>net stop MySQL MySQL 服務正在中止. MySQL 服務已成功中止。 C:\Windows\system32>net start MySQL MySQL 服務正在啓動 . MySQL 服務已經啓動成功。 C:\Windows\system32>mysql Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 1 Server version: 5.6.39 MySQL Community Server (GPL) Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved. Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners. Type 'help;' or '\h' for help. Type '\c' to clear the current input statement. mysql> \s -------------- mysql Ver 14.14 Distrib 5.6.39, for Win64 (x86_64) Connection id: 1 Current database: Current user: ODBC@localhost SSL: Not in use Using delimiter: ; Server version: 5.6.39 MySQL Community Server (GPL) Protocol version: 10 Connection: localhost via TCP/IP Server characterset: utf8 Db characterset: utf8 Client characterset: utf8 Conn. characterset: utf8 TCP port: 3306 Uptime: 13 sec Threads: 1 Questions: 5 Slow queries: 0 Opens: 67 Flush tables: 1 Open tabl es: 60 Queries per second avg: 0.384 -------------- mysql> show variables like 'character%'; +--------------------------+----------------------------------------+ | Variable_name | Value | +--------------------------+----------------------------------------+ | character_set_client | utf8 | | character_set_connection | utf8 | | character_set_database | utf8 | | character_set_filesystem | binary | | character_set_results | utf8 | | character_set_server | utf8 | | character_set_system | utf8 | | character_sets_dir | C:\mysql-5.6.39-winx64\share\charsets\ | +--------------------------+----------------------------------------+ 8 rows in set (0.00 sec)
跟數據有關的文件都放在data目錄下
SQL語句:
操做數據庫就是操做文件夾
增
create database db1 charset utf8;
查
show create database db1;
show databases; #查看全部的庫
改
alter database db1 charset gbk;
刪
drop database db1;
C:\Users\Administrator>mysql -uroot -p Enter password: Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 2 Server version: 5.6.39 MySQL Community Server (GPL) Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved. Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners. Type 'help;' or '\h' for help. Type '\c' to clear the current input statement. mysql> create database db1 charset utf8; Query OK, 1 row affected (0.06 sec) mysql> show create database db1; +----------+--------------------------------------------------------------+ | Database | Create Database | +----------+--------------------------------------------------------------+ | db1 | CREATE DATABASE `db1` /*!40100 DEFAULT CHARACTER SET utf8 */ | +----------+--------------------------------------------------------------+ 1 row in set (0.06 sec) mysql> show databases; +--------------------+ | Database | +--------------------+ | information_schema | | db1 | | mysql | | performance_schema | | test | +--------------------+ 5 rows in set (0.14 sec) mysql> alter database db1 charset gbk; Query OK, 1 row affected (0.00 sec) mysql> show create database db1; +----------+-------------------------------------------------------------+ | Database | Create Database | +----------+-------------------------------------------------------------+ | db1 | CREATE DATABASE `db1` /*!40100 DEFAULT CHARACTER SET gbk */ | +----------+-------------------------------------------------------------+ 1 row in set (0.00 sec) mysql> drop database db1; Query OK, 0 rows affected (0.26 sec)
造表就是在硬盤上操做文件;.frm就是表標題之類的、.db就是表數據;
切換文件夾:use db1;
查看當前所在文件夾:select database();
增
create table t1(id int,name char);
查
show create table t1;
show tables;
desc t1;
改
alter table t1 modify name char(6);
alter table t1 change name NAME char(7);
刪
drop table t1;
C:\Users\Administrator>mysql -uroot -p Enter password: Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 3 Server version: 5.6.39 MySQL Community Server (GPL) Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved. Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners. Type 'help;' or '\h' for help. Type '\c' to clear the current input statement. mysql> create database db1 charset utf8; Query OK, 1 row affected (0.00 sec) mysql> use db1; Database changed mysql> select database(); +------------+ | database() | +------------+ | db1 | +------------+ 1 row in set (0.00 sec) mysql> create table t1(id int,name char); Query OK, 0 rows affected (1.65 sec) mysql> show create table t1; +-------+------------------------------------------------------------------------------------------------------ | Table | Create Table | +-------+---------------------------------------------------------------------------------------------------- | t1 | CREATE TABLE `t1` ( `id` int(11) DEFAULT NULL, `name` char(6) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 | +-------+----------------------------------------------------------------------- 1 row in set (0.12 sec) mysql> show tables; +---------------+ | Tables_in_db1 | +---------------+ | t1 | +---------------+ 1 row in set (0.00 sec) mysql> desc t1; +-------+---------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------+---------+------+-----+---------+-------+ | id | int(11) | YES | | NULL | | | name | char(6) | YES | | NULL | | +-------+---------+------+-----+---------+-------+ 2 rows in set (0.01 sec) mysql> alter table t1 change name NAME char(7); Query OK, 0 rows affected (1.31 sec) Records: 0 Duplicates: 0 Warnings: 0 mysql> desc t1; +-------+---------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------+---------+------+-----+---------+-------+ | id | int(11) | YES | | NULL | | | NAME | char(7) | YES | | NULL | | +-------+---------+------+-----+---------+-------+ 2 rows in set (0.05 sec) mysql> drop table t1; Query OK, 0 rows affected (0.23 sec) mysql> show tables; Empty set (0.00 sec)
在表裏邊操做
增
insert t1(id,name) values(1,'egon1'),(2,'egon2'),(3,'egon3');
查
select id,name from db1.t1;
select * from db1.t1;(不推薦使用,測試的時候能夠用)
改
update db1.t1 set name='SB';
update db1.t1 set name='ALEX' where id=2;
刪
delete from t1;
delete from t1 where id=2;
mysql> use db1; Database changed mysql> insert t1(id,name) values(1,'egon1'),(2,'egon2'),(3,'egon3'); Query OK, 3 rows affected (0.53 sec) Records: 3 Duplicates: 0 Warnings: 0 mysql> select id,name from db1.t1; +------+-------+ | id | name | +------+-------+ | 1 | egon1 | | 2 | egon2 | | 3 | egon3 | +------+-------+ 3 rows in set (0.00 sec) mysql> select id from db1.t1; +------+ | id | +------+ | 1 | | 2 | | 3 | +------+ 3 rows in set (0.00 sec) mysql> select * from db1.t1; +------+-------+ | id | name | +------+-------+ | 1 | egon1 | | 2 | egon2 | | 3 | egon3 | +------+-------+ 3 rows in set (0.00 sec) mysql> update db1.t1 set name='SB'; Query OK, 3 rows affected (0.10 sec) Rows matched: 3 Changed: 3 Warnings: 0 mysql> update db1.t1 set name='alex' where id=2; Query OK, 1 row affected (0.16 sec) Rows matched: 1 Changed: 1 Warnings: 0 mysql> select * from db1.t1; +------+------+ | id | name | +------+------+ | 1 | SB | | 2 | alex | | 3 | SB | +------+------+ 3 rows in set (0.00 sec) mysql> delete from t1 where id=2; Query OK, 1 row affected (0.12 sec)
系統數據庫
information_schema: 虛擬庫,不佔用磁盤空間,存儲的是數據庫啓動後的一些參數,如用戶表信息、列信息、權限信息、字符信息等
performance_schema: MySQL 5.5開始新增一個數據庫:主要用於收集數據庫服務器性能參數,記錄處理查詢請求時發生的各類事件、鎖等現象
mysql: 受權庫,主要存儲系統用戶的權限信息
test: MySQL數據庫系統自動建立的測試數據庫
建立數據庫
CREATE DATABASE 數據庫名 charset utf8;
命名規則:能夠由字母、數字、下劃線、@、#、$;區分大小寫;惟一性;不能使用關鍵字如 create select;不能單獨使用數字;最長128位
查看數據庫 show databases; ##全部的庫 show create database db1; select database(); ##當前選擇的庫 選擇數據庫 USE 數據庫名; 刪除數據庫 DROP DATABASE 數據庫名; 修改數據庫 alter database db1 charset utf8;
能夠用 help create help create database
一、什麼是存儲引擎?
存儲引擎就是表的類型
二、查看MySQL支持的存儲引擎
show engines;
show engines\G #查看全部支持的存儲引擎
show variables like 'storage_engine%'; #查看正在使用的存儲引擎
三、指定表類型/存儲引擎
create table t1(id int)engine=innodb;
create table t2(id int)engine=memory; #數據丟進去存到內存裏邊 #須要把mysql關了內存就清除了
create table t3(id int)engine=blackhole; #黑洞,數據丟進去就沒了
create table t4(id int)engine=myisam; #.frm表結構;.MYD是它的表data文件;.MYI索引文件;
insert into t1 values(1);
insert into t2 values(1);
insert into t3 values(1);
insert into t4 values(1)
mysql> show engines; +--------------------+---------+----------------------------------------------------------------+--------------+------+------------+ | Engine | Support | Comment | Transactions | XA | Savepoints | +--------------------+---------+----------------------------------------------------------------+--------------+------+------------+ | FEDERATED | NO | Federated MySQL storage engine | NULL | NULL | NULL | | MRG_MYISAM | YES | Collection of identical MyISAM tables | NO | NO | NO | | MyISAM | YES | MyISAM storage engine | NO | NO | NO | | BLACKHOLE | YES | /dev/null storage engine (anything you write to it disappears) | NO | NO | NO | | CSV | YES | CSV storage engine | NO | NO | NO | | MEMORY | YES | Hash based, stored in memory, useful for temporary tables | NO | NO | NO | | ARCHIVE | YES | Archive storage engine | NO | NO | NO | | InnoDB | DEFAULT | Supports transactions, row-level locking, and foreign keys | YES | YES | YES | | PERFORMANCE_SCHEMA | YES | Performance Schema | NO | NO | NO | +--------------------+---------+----------------------------------------------------------------+--------------+------+------------+ 9 rows in set (0.08 sec) mysql> show engines\G *************************** 1. row *************************** Engine: FEDERATED Support: NO Comment: Federated MySQL storage engine Transactions: NULL XA: NULL Savepoints: NULL *************************** 2. row *************************** Engine: MRG_MYISAM Support: YES Comment: Collection of identical MyISAM tables Transactions: NO XA: NO Savepoints: NO *************************** 3. row *************************** Engine: MyISAM Support: YES Comment: MyISAM storage engine Transactions: NO XA: NO Savepoints: NO *************************** 4. row *************************** Engine: BLACKHOLE Support: YES Comment: /dev/null storage engine (anything you write to it disappears) Transactions: NO XA: NO Savepoints: NO *************************** 5. row *************************** Engine: CSV Support: YES Comment: CSV storage engine Transactions: NO XA: NO Savepoints: NO *************************** 6. row *************************** Engine: MEMORY Support: YES Comment: Hash based, stored in memory, useful for temporary tables Transactions: NO XA: NO Savepoints: NO *************************** 7. row *************************** Engine: ARCHIVE Support: YES Comment: Archive storage engine Transactions: NO XA: NO Savepoints: NO *************************** 8. row *************************** Engine: InnoDB Support: DEFAULT Comment: Supports transactions, row-level locking, and foreign keys Transactions: YES XA: YES Savepoints: YES *************************** 9. row *************************** Engine: PERFORMANCE_SCHEMA Support: YES Comment: Performance Schema Transactions: NO XA: NO Savepoints: NO 9 rows in set (0.00 sec)
mysql> create database db2; Query OK, 1 row affected (0.01 sec) mysql> use db2; Database changed mysql> create table t1(id int)engine=innodb; Query OK, 0 rows affected (0.64 sec) mysql> create table t2(id int)engine=memory; Query OK, 0 rows affected (0.21 sec) mysql> create table t3(id int)engine=blackhole; Query OK, 0 rows affected (0.26 sec) mysql> create table t4(id int)engine=myisam; Query OK, 0 rows affected (0.17 sec) mysql> insert into t1 values(1); Query OK, 1 row affected (0.31 sec) mysql> insert into t2 values(1); Query OK, 1 row affected (0.00 sec) mysql> insert into t3 values(1); Query OK, 1 row affected (0.02 sec) mysql> insert into t4 values(1); Query OK, 1 row affected (0.10 sec) mysql> select * from t1; #innodb +------+ | id | +------+ | 1 | +------+ 1 row in set (0.00 sec) mysql> select * from t4; #myisam +------+ | id | +------+ | 1 | +------+ 1 row in set (0.00 sec) mysql> select * from t3; #blackhole Empty set (0.00 sec) mysql> select * from t2; +------+ | id | +------+ | 1 | +------+ 1 row in set (0.00 sec) mysql> exit Bye C:\Windows\system32>net stop MySQL MySQL 服務正在中止. MySQL 服務已成功中止。 C:\Windows\system32>net start MySQL MySQL 服務正在啓動 .. MySQL 服務已經啓動成功。 C:\Users\Administrator>mysql -uroot -p Enter password: Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 2 Server version: 5.6.39 MySQL Community Server (GPL) Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved. Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners. Type 'help;' or '\h' for help. Type '\c' to clear the current input statement. mysql> select * from db2.t2; #數據丟到內存裏邊了,從新啓動就沒了 Empty set (0.00 sec)
表至關於文件,表中的一條記錄就至關於文件的一行內容,不一樣的是,表中的一條記錄有對應的標題,稱爲表的字段;
id,name,age,sex 稱爲字段,其他的,一行內容稱爲一條記錄
語法: create table 表名( 字段名1 類型[(寬度) 約束條件], 字段名2 類型[(寬度) 約束條件], 字段名3 類型[(寬度) 約束條件] ); #注意: 1. 在同一張表中,字段名是不能相同 2. 寬度和約束條件可選 3. 字段名和類型是必須的
查看錶:
use db2
desc t4; #查看錶結構、字段
show create table t4; #查看錶的詳細信息
show create table t4\G
show create table mysql.user\G
修改表結構:
語法: 1. 修改表名 ALTER TABLE 表名 RENAME 新表名; 2. 增長字段 ALTER TABLE 表名 ADD 字段名 數據類型 [完整性約束條件…], ADD 字段名 數據類型 [完整性約束條件…]; ALTER TABLE 表名 ADD 字段名 數據類型 [完整性約束條件…] FIRST; ALTER TABLE 表名 ADD 字段名 數據類型 [完整性約束條件…] AFTER 字段名; 3. 刪除字段 ALTER TABLE 表名 DROP 字段名; 4. 修改字段 ALTER TABLE 表名 MODIFY 字段名 數據類型 [完整性約束條件…]; ALTER TABLE 表名 CHANGE 舊字段名 新字段名 舊數據類型 [完整性約束條件…]; ALTER TABLE 表名 CHANGE 舊字段名 新字段名 新數據類型 [完整性約束條件…];
複製表:
複製表結構+記錄 (key不會複製: 主鍵、外鍵和索引) mysql> create table new_service select * from service; 只複製表結構(兩種方法:1.是在條件爲假的狀況下;2.用like ) mysql> select * from service where 1=2; //條件爲假,查不到任何記錄 Empty set (0.00 sec) mysql> create table new1_service select * from service where 1=2; Query OK, 0 rows affected (0.00 sec) Records: 0 Duplicates: 0 Warnings: 0 mysql> create table t4 like employees;
mysql> select * from mysql.user; +-----------+------+----------+-------------+-------------+-------------+-------------+-------------+-----------+-------------+---------------+--------------+-- | Host | User | Password | Select_priv | Insert_priv | Update_priv | Delete _priv | Create_priv | Drop_priv | Reload_priv | Shutdown_priv | Process_priv | F ile_priv | Grant_priv | References_priv | Index_priv | Alter_priv | Show_db_priv | Super_pri............................
.........................................##太多了此處省略
4 rows in set (0.00 sec) mysql> select * from mysql.user\G *************************** 1. row *************************** Host: localhost User: root Password: Select_priv: Y Insert_priv: Y Update_priv: Y Delete_priv: Y Create_priv: Y Drop_priv: Y Reload_priv: Y Shutdown_priv: Y Process_priv: Y File_priv: Y Grant_priv: Y References_priv: Y Index_priv: Y Alter_priv: Y Show_db_priv: Y Super_priv: Y Create_tmp_table_priv: Y Lock_tables_priv: Y Execute_priv: Y Repl_slave_priv: Y Repl_client_priv: Y Create_view_priv: Y Show_view_priv: Y Create_routine_priv: Y Alter_routine_priv: Y Create_user_priv: Y Event_priv: Y Trigger_priv: Y Create_tablespace_priv: Y ssl_type: ssl_cipher: x509_issuer: x509_subject: max_questions: 0 max_updates: 0 max_connections: 0 max_user_connections: 0 plugin: mysql_native_password authentication_string: password_expired: N *************************** 2. row *************************** Host: 127.0.0.1 User: root Password: Select_priv: Y Insert_priv: Y Update_priv: Y Delete_priv: Y Create_priv: Y Drop_priv: Y Reload_priv: Y Shutdown_priv: Y Process_priv: Y File_priv: Y Grant_priv: Y References_priv: Y Index_priv: Y Alter_priv: Y Show_db_priv: Y Super_priv: Y Create_tmp_table_priv: Y Lock_tables_priv: Y Execute_priv: Y Repl_slave_priv: Y Repl_client_priv: Y Create_view_priv: Y Show_view_priv: Y Create_routine_priv: Y Alter_routine_priv: Y Create_user_priv: Y Event_priv: Y Trigger_priv: Y Create_tablespace_priv: Y ssl_type: ssl_cipher: x509_issuer: x509_subject: max_questions: 0 max_updates: 0 max_connections: 0 max_user_connections: 0 plugin: mysql_native_password authentication_string: password_expired: N *************************** 3. row *************************** Host: ::1 User: root Password: Select_priv: Y Insert_priv: Y Update_priv: Y Delete_priv: Y Create_priv: Y Drop_priv: Y Reload_priv: Y Shutdown_priv: Y Process_priv: Y File_priv: Y Grant_priv: Y References_priv: Y Index_priv: Y Alter_priv: Y Show_db_priv: Y Super_priv: Y Create_tmp_table_priv: Y Lock_tables_priv: Y Execute_priv: Y Repl_slave_priv: Y Repl_client_priv: Y Create_view_priv: Y Show_view_priv: Y Create_routine_priv: Y Alter_routine_priv: Y Create_user_priv: Y Event_priv: Y Trigger_priv: Y Create_tablespace_priv: Y ssl_type: ssl_cipher: x509_issuer: x509_subject: max_questions: 0 max_updates: 0 max_connections: 0 max_user_connections: 0 plugin: mysql_native_password authentication_string: password_expired: N *************************** 4. row *************************** Host: localhost User: Password: Select_priv: N Insert_priv: N Update_priv: N Delete_priv: N Create_priv: N Drop_priv: N Reload_priv: N Shutdown_priv: N Process_priv: N File_priv: N Grant_priv: N References_priv: N Index_priv: N Alter_priv: N Show_db_priv: N Super_priv: N Create_tmp_table_priv: N Lock_tables_priv: N Execute_priv: N Repl_slave_priv: N Repl_client_priv: N Create_view_priv: N Show_view_priv: N Create_routine_priv: N Alter_routine_priv: N Create_user_priv: N Event_priv: N Trigger_priv: N Create_tablespace_priv: N ssl_type: ssl_cipher: x509_issuer: x509_subject: max_questions: 0 max_updates: 0 max_connections: 0 max_user_connections: 0 plugin: mysql_native_password authentication_string: NULL password_expired: N 4 rows in set (0.00 sec)
mysql> select host,user from mysql.user; +-----------+------+ | host | user | +-----------+------+ | 127.0.0.1 | root | | ::1 | root | | localhost | | | localhost | root | +-----------+------+ 4 rows in set (0.00 sec)
mysql> create database db3 charset utf8; Query OK, 1 row affected (0.00 sec) mysql> use db3; Database changed mysql> select host,user from mysql.user; +-----------+------+ | host | user | +-----------+------+ | 127.0.0.1 | root | | ::1 | root | | localhost | | | localhost | root | +-----------+------+ 4 rows in set (0.00 sec) mysql> create table t1 select host,user from mysql.user; #別往屏幕上丟了,丟給t1,這就是複製表 Query OK, 4 rows affected (0.78 sec) Records: 4 Duplicates: 0 Warnings: 0 mysql> desc t1; #表結構只有host和user +-------+----------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------+----------+------+-----+---------+-------+ | host | char(60) | NO | | | | | user | char(16) | NO | | | | +-------+----------+------+-----+---------+-------+ 2 rows in set (0.01 sec) mysql> select * from t1; #查看下它的記錄 +-----------+------+ | host | user | +-----------+------+ | 127.0.0.1 | root | | ::1 | root | | localhost | | | localhost | root | +-----------+------+ 4 rows in set (0.00 sec) #########只要表結構,不要記錄 mysql> select host,user from mysql.user; +-----------+------+ | host | user | +-----------+------+ | 127.0.0.1 | root | | ::1 | root | | localhost | | | localhost | root | +-----------+------+ 4 rows in set (0.00 sec) mysql> select host,user from mysql.user where 1>5; #在條件爲假的狀況下實現, 只要表結構,不要記錄。 Empty set (0.07 sec) mysql> create table t2 select host,user from mysql.user where 1>5; Query OK, 0 rows affected (0.57 sec) Records: 0 Duplicates: 0 Warnings: 0 mysql> desc t2; +-------+----------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------+----------+------+-----+---------+-------+ | host | char(60) | NO | | | | | user | char(16) | NO | | | | +-------+----------+------+-----+---------+-------+ 2 rows in set (0.01 sec) mysql> select * from t2; Empty set (0.00 sec) ####只拷貝表結構用like 就能夠了,沒有數據 mysql> create table t3 like mysql.user; Query OK, 0 rows affected (0.66 sec) mysql> desc t3; +------------------------+-----------------------------------+------+-----+-----------------------+-------+ | Field | Type | Null | Key | Default | Extra | +------------------------+-----------------------------------+------+-----+-----------------------+-------+ | Host | char(60) | NO | PRI | | | | User | char(16) | NO | PRI | | | | Password | char(41) | NO | | | | | Select_priv | enum('N','Y') | NO | | N | | | Insert_priv | enum('N','Y') | NO | | N | | | Update_priv | enum('N','Y') | NO | | N | | | Delete_priv | enum('N','Y') | NO | | N | | | Create_priv | enum('N','Y') | NO | | N | | | Drop_priv | enum('N','Y') | NO | | N | | | Reload_priv | enum('N','Y') | NO | | N | | | Shutdown_priv | enum('N','Y') | NO | | N | | | Process_priv | enum('N','Y') | NO | | N | | | File_priv | enum('N','Y') | NO | | N | | | Grant_priv | enum('N','Y') | NO | | N | | | References_priv | enum('N','Y') | NO | | N | | | Index_priv | enum('N','Y') | NO | | N | | | Alter_priv | enum('N','Y') | NO | | N | | | Show_db_priv | enum('N','Y') | NO | | N | | | Super_priv | enum('N','Y') | NO | | N | | | Create_tmp_table_priv | enum('N','Y') | NO | | N | | | Lock_tables_priv | enum('N','Y') | NO | | N | | | Execute_priv | enum('N','Y') | NO | | N | | | Repl_slave_priv | enum('N','Y') | NO | | N | | | Repl_client_priv | enum('N','Y') | NO | | N | | | Create_view_priv | enum('N','Y') | NO | | N | | | Show_view_priv | enum('N','Y') | NO | | N | | | Create_routine_priv | enum('N','Y') | NO | | N | | | Alter_routine_priv | enum('N','Y') | NO | | N | | | Create_user_priv | enum('N','Y') | NO | | N | | | Event_priv | enum('N','Y') | NO | | N | | | Trigger_priv | enum('N','Y') | NO | | N | | | Create_tablespace_priv | enum('N','Y') | NO | | N | | | ssl_type | enum('','ANY','X509','SPECIFIED') | NO | | | | | ssl_cipher | blob | NO | | NULL | | | x509_issuer | blob | NO | | NULL | | | x509_subject | blob | NO | | NULL | | | max_questions | int(11) unsigned | NO | | 0 | | | max_updates | int(11) unsigned | NO | | 0 | | | max_connections | int(11) unsigned | NO | | 0 | | | max_user_connections | int(11) unsigned | NO | | 0 | | | plugin | char(64) | YES | | mysq l_native_password | | | authentication_string | text | YES | | NULL | | | password_expired | enum('N','Y') | NO | | N | | +------------------------+-----------------------------------+------+-----+-----------------------+-------+ 43 rows in set (0.03 sec) mysql> desc mysql.user; ##跟上邊操做同樣 +------------------------+-----------------------------------+------+-----+-----------------------+-------+ | Field | Type | Null | Key | Default | Extra | +------------------------+-----------------------------------+------+-----+-----------------------+-------+ | Host | char(60) | NO | PRI | | | | User | char(16) | NO | PRI | | | | Password | char(41) | NO | | | | | Select_priv | enum('N','Y') | NO | | N | | | Insert_priv | enum('N','Y') | NO | | N | | | Update_priv | enum('N','Y') | NO | | N | | | Delete_priv | enum('N','Y') | NO | | N | | | Create_priv | enum('N','Y') | NO | | N | | | Drop_priv | enum('N','Y') | NO | | N | | | Reload_priv | enum('N','Y') | NO | | N | | | Shutdown_priv | enum('N','Y') | NO | | N | | | Process_priv | enum('N','Y') | NO | | N | | | File_priv | enum('N','Y') | NO | | N | | | Grant_priv | enum('N','Y') | NO | | N | | | References_priv | enum('N','Y') | NO | | N | | | Index_priv | enum('N','Y') | NO | | N | | | Alter_priv | enum('N','Y') | NO | | N | | | Show_db_priv | enum('N','Y') | NO | | N | | | Super_priv | enum('N','Y') | NO | | N | | | Create_tmp_table_priv | enum('N','Y') | NO | | N | | | Lock_tables_priv | enum('N','Y') | NO | | N | | | Execute_priv | enum('N','Y') | NO | | N | | | Repl_slave_priv | enum('N','Y') | NO | | N | | | Repl_client_priv | enum('N','Y') | NO | | N | | | Create_view_priv | enum('N','Y') | NO | | N | | | Show_view_priv | enum('N','Y') | NO | | N | | | Create_routine_priv | enum('N','Y') | NO | | N | | | Alter_routine_priv | enum('N','Y') | NO | | N | | | Create_user_priv | enum('N','Y') | NO | | N | | | Event_priv | enum('N','Y') | NO | | N | | | Trigger_priv | enum('N','Y') | NO | | N | | | Create_tablespace_priv | enum('N','Y') | NO | | N | | | ssl_type | enum('','ANY','X509','SPECIFIED') | NO | | | | | ssl_cipher | blob | NO | | NULL | | | x509_issuer | blob | NO | | NULL | | | x509_subject | blob | NO | | NULL | | | max_questions | int(11) unsigned | NO | | 0 | | | max_updates | int(11) unsigned | NO | | 0 | | | max_connections | int(11) unsigned | NO | | 0 | | | max_user_connections | int(11) unsigned | NO | | 0 | | | plugin | char(64) | YES | | mysq l_native_password | | | authentication_string | text | YES | | NULL | | | password_expired | enum('N','Y') | NO | | N | | +------------------------+-----------------------------------+------+-----+-----------------------+-------+ 43 rows in set (0.01 sec) mysql> select * from t3; Empty set (0.06 sec)
#1. 數字: 整型:tinyinit int bigint 小數: float :在位數比較短的狀況下不精準 double :在位數比較長的狀況下不精準 0.000001230123123123 存成:0.000001230000 decimal:(若是用小數,則用推薦使用decimal) 精準 內部原理是以字符串形式去存 #2. 字符串: char(10):簡單粗暴,浪費空間,存取速度快 root存成root000000 varchar:精準,節省空間,存取速度慢 sql優化:建立表時,定長的類型往前放,變長的日後放 好比性別 好比地址或描述信息 >255個字符,超了就把文件路徑存放到數據庫中。 好比圖片,視頻等找一個文件服務器,數據庫中只存路徑或url。 #3. 時間類型: 最經常使用:datetime #4. 枚舉類型與集合類型
驗證表的數值類型 tinyint
======================================== tinyint[(m)] [unsigned] [zerofill] 小整數,數據類型用於保存一些範圍的整數數值範圍: 有符號: -128 ~ 127 無符號: 0 ~ 255 PS: MySQL中無布爾值,使用tinyint(1)構造。 ======================================== int[(m)][unsigned][zerofill] 整數,數據類型用於保存一些範圍的整數數值範圍: 有符號: -2147483648 ~ 2147483647 無符號: 0 ~ 4294967295 ======================================== bigint[(m)][unsigned][zerofill] 大整數,數據類型用於保存一些範圍的整數數值範圍: 有符號: -9223372036854775808 ~ 9223372036854775807 無符號: 0 ~ 18446744073709551615
zerofill 使用說明,例如 int(5)表示當數值寬度小於 5 位的時候在數字前面加’0’填滿寬度,若是不顯示指定寬度則默認爲 int(11),zerofill默認爲int(10)。注:當使用zerofill 時,默認會自動加unsigned(無符號)屬性,使用unsigned屬性後,數值範圍是原值的2倍,例如,有符號爲-128~+127,無符號爲0~256。
mysql> create database db4; Query OK, 1 row affected (0.00 sec) mysql> use db4; Database changed mysql> create table t1(x tinyint); ##默認是有符號zerofill -128~127 Query OK, 0 rows affected (0.52 sec) mysql> insert into t1 values(-1); Query OK, 1 row affected (0.12 sec) mysql> select * from t1; +------+ | x | +------+ | -1 | +------+ 1 row in set (0.00 sec) mysql> insert into t1 values(-129),(128); #超過範圍win7系統報錯了 ERROR 1264 (22003): Out of range value for column 'x' at row 1 mysql> create table t2(x tinyint unsigned); #建立無符號的,默認都是有符號的;有符號即數字前有正、負號 Query OK, 0 rows affected (0.57 sec) #0-255 mysql> insert into t2 values(-1),(256); ERROR 1264 (22003): Out of range value for column 'x' at row 1 mysql> insert into t2 values(-1),(255); ERROR 1264 (22003): Out of range value for column 'x' at row 1 mysql> insert into t2 values(0),(255); Query OK, 2 rows affected (0.13 sec) Records: 2 Duplicates: 0 Warnings: 0 mysql> select * from t2; +------+ | x | +------+ | 0 | | 255 | +------+ 2 rows in set (0.00 sec) #寬度 字節 int(1)後邊加了個寬度,這是個坑;整型後邊那個寬度並非它的存儲寬度,而是它的顯示寬度;存儲寬度是在指定類型以後就已經默認定了;顯示寬度也沒有必要指定,它會給你默認添加的,
足夠在範圍之內;除此以前,其餘數據類型的寬度就是它的存儲寬度
精度
====================================== #FLOAT[(M,D)] [UNSIGNED] [ZEROFILL] 定義: 單精度浮點數(非準確小數值),m是數字總個數,d是小數點後個數。m最大值爲255,d最大值爲30 有符號: -3.402823466E+38 to -1.175494351E-38, 1.175494351E-38 to 3.402823466E+38 無符號: 1.175494351E-38 to 3.402823466E+38 精確度: **** 隨着小數的增多,精度變得不許確 **** ====================================== #DOUBLE[(M,D)] [UNSIGNED] [ZEROFILL] 定義: 雙精度浮點數(非準確小數值),m是數字總個數,d是小數點後個數。m最大值爲255,d最大值爲30 有符號: -1.7976931348623157E+308 to -2.2250738585072014E-308 2.2250738585072014E-308 to 1.7976931348623157E+308 無符號: 2.2250738585072014E-308 to 1.7976931348623157E+308 精確度: ****隨着小數的增多,精度比float要高,但也會變得不許確 **** ====================================== decimal[(m[,d])] [unsigned] [zerofill] 定義: 準確的小數值,m是數字總個數(負號不算),d是小數點後個數。 m最大值爲65,d最大值爲30。 精確度: **** 隨着小數的增多,精度始終準確 **** 對於精確數值計算時須要用此類型 decaimal可以存儲精確值的緣由在於其內部按照字符串存儲。
mysql> create table t8(x float(255,30)); Query OK, 0 rows affected (0.59 sec) mysql> create table t9(x double(255,30)); Query OK, 0 rows affected (0.53 sec) mysql> create table t10(x decimal(65,30)); Query OK, 0 rows affected (1.38 sec) mysql> insert into t8 values(1.111111111111111111111111111111);##隨着小數位數增多,精度開始不許確 Query OK, 1 row affected (0.26 sec) mysql> insert into t9 values(1.111111111111111111111111111111);#精度要比float準確點,但隨着小數的增多,一樣變得不許確; Query OK, 1 row affected (0.16 sec) mysql> insert into t10 values(1.111111111111111111111111111111); ##精度始終準確,d爲30,只保留30位小數 Query OK, 1 row affected (0.08 sec) mysql> select *from t8; +----------------------------------+ | x | +----------------------------------+ | 1.111111164093017600000000000000 | +----------------------------------+ 1 row in set (0.00 sec) mysql> select * from t9; +----------------------------------+ | x | +----------------------------------+ | 1.111111111111111200000000000000 | +----------------------------------+ 1 row in set (0.00 sec) mysql> select * from t10; +----------------------------------+ | x | +----------------------------------+ | 1.111111111111111111111111111111 | +----------------------------------+ 1 row in set (0.00 sec)
日期類型
create table student(
id int,
name char(6), # 表最大存儲6個字符
born_year year,#年
birth_date date,#年月日
class_time time, #時分秒
reg_time datetime #年月日時分秒
);
insert into student values
(1,'egon',now(),now(),now(),now() );
insert into student values
(2,'alex',"1997","1997-12-12","12:12:12","2017-12-12 12:12:12");
mysql> create table student( -> id int, -> name char(6), -> born_year year, #年 -> birth_date date, #年月日 -> class_time time, #時分秒 -> reg_time datetime #年月日時分秒 -> ); Query OK, 0 rows affected (0.56 sec) mysql> insert into student values -> (1,'kris',now(),now(),now(),now()); Query OK, 1 row affected, 1 warning (0.25 sec) mysql> select * from student; +------+------+-----------+------------+------------+---------------------+ | id | name | born_year | birth_date | class_time | reg_time | +------+------+-----------+------------+------------+---------------------+ | 1 | kris | 2018 | 2018-04-26 | 13:57:00 | 2018-04-26 13:57:00 | +------+------+-----------+------------+------------+---------------------+ 1 row in set (0.00 sec) mysql> insert into student values -> (2,'alex',"1997","1997-12-12","12:12:12","2017-12-12 12:12:12"); Query OK, 1 row affected (0.12 sec) mysql> select * from student; +------+------+-----------+------------+------------+---------------------+ | id | name | born_year | birth_date | class_time | reg_time | +------+------+-----------+------------+------------+---------------------+ | 1 | kris | 2018 | 2018-04-26 | 13:57:00 | 2018-04-26 13:57:00 | | 2 | alex | 1997 | 1997-12-12 | 12:12:12 | 2017-12-12 12:12:12 | +------+------+-----------+------------+------------+---------------------+ 2 rows in set (0.00 sec) ->\c ##爲終止運行
字符類型
char: 定長 不夠的給你補上
varchar: 變長 傳幾個給你寫幾個,不要超過字符個數
#寬度指的是字符的個數
create table t13(name char(5));
create table t14(name varchar(5));
insert into t13 values('李傑 '); #'李傑 ' 後邊有3個空格
insert into t14 values('李傑 '); #'李傑 ' 後邊有1個空格
select char_length(name) from t13; #5 把name傳給這個函數,統計查過結果的字符的長度
select char_length(name) from t14; #3
打開 pad_char_to_full_length SQL 模式 SET sql_mode = 'PAD_CHAR_TO_FULL_LENGTH';這樣在檢索或者查詢時,查出的結果會自動刪除尾部的空格。
select name from t13 where name='李傑';
select name from t13 where name like '李傑';
mysql> create table t13(name char(5)); Query OK, 0 rows affected (0.64 sec) mysql> create table t14(name varchar(5)); Query OK, 0 rows affected (0.62 sec) mysql> insert into t13 values('alex'); Query OK, 1 row affected (0.12 sec) mysql> insert into t14 values('alex'); Query OK, 1 row affected (0.12 sec) mysql> mysql> select char_length(name) from t13; # char_length是查看字符數 #你取的時候它把後邊的0給你省掉了;寫入的時候不會省;存的時候是種存儲機制,
#對於取能夠加where條件,知足條件了再查出來;無論怎麼存,在取的時候,mysql只會按照值進行匹造並不會管末尾有幾個值;因此說在取的時候後邊有幾個空格沒有用。 +-------------------+ | char_length(name) | +-------------------+ | 4 | +-------------------+ 1 row in set (0.14 sec) mysql> SET sql_mode = 'PAD_CHAR_TO_FULL_LENGTH'; Query OK, 0 rows affected (0.15 sec) #讓它顯出原型來 mysql> select char_length(name) from t13; #5 +-------------------+ | char_length(name) | +-------------------+ | 5 | +-------------------+ 1 row in set (0.00 sec) #######末尾去空格###(使用 where或者like兩種方法 ) mysql> select name from t13 where name='alex'; +-------+ | name | +-------+ | alex | +-------+ 1 row in set (0.14 sec) mysql> select name from t13 where name='alex '; #無論後邊有幾個空格,均可以忽略,可是前面有空格就查不到了。 +-------+ | name | +-------+ | alex | +-------+ 1 row in set (0.00 sec) mysql> select name from t13 where name=' alex'; Empty set (0.00 sec) mysql> select name from t13 where name like'alex'; Empty set (0.02 sec) mysql> select name from t13 where name like'alex '; Empty set (0.00 sec) mysql> select name from t13 where name like'alex'; Empty set (0.00 sec) mysql> select name from t13 where name like'alex '; #like必須保證它的完整性,否則查不到 +-------+ | name | +-------+ | alex | +-------+ 1 row in set (0.00 sec)
char填充空格來知足固定長度,可是在查詢時卻會很不要臉地刪除尾部的空格(裝做本身好像沒有浪費過空間同樣),而後修改sql_mode讓其現出原形
雖然 CHAR 和 VARCHAR 的存儲方式不太相同,可是對於兩個字符串的比較,都只比 較其值,忽略 CHAR 值存在的右填充,即便將 SQL _MODE 設置爲 PAD_CHAR_TO_FULL_ LENGTH 也同樣,,但這不適用於like;
name char(5) #char類型優勢是簡單粗暴,無論你有多少個數據,存5個取五個,存儲效率很是快;缺點是浪費空間;(大部分場景用char)
egon |alex |wxx |
name varchar(5) #varchar類型優勢是更加節省空間,存數據更加精準,但存的時候速度慢,先存頭再存數據,取的時候也是先讀頭才知道取多少個數據
1bytes+egon|1bytes+alex|1bytes+wxx|
4+egon|4+alex|3+wxx|
建表的時候把定長的數據往前放,儘可能不要混着用。
枚舉類型與集合類型
字段的值只能在給定範圍中選擇,如單選框,多選框
enum 單選 只能在給定的範圍內選一個值,如性別 sex 男male/女female
set 多選 在給定的範圍內能夠選擇一個或一個以上的值(愛好1,愛好2,愛好3...)
create table consumer(
id int,
name char(16),
sex enum('male','female','other'),
level enum('vip1','vip2','vip3'),
hobbies set('play','music','read','run')
);
insert into consumer values
(1,'egon','male','vip2','music,read');
insert into consumer values
(1,'egon','xxxxx','vip2','music,read');
mysql> create table consumer( -> id int, -> name char(16), -> sex enum('male','female','other'), -> level enum('vip1','vip2','vip3'), -> hobbies set('play','music','read','run') -> ); Query OK, 0 rows affected (0.62 sec) mysql> mysql> mysql> insert into consumer values -> (1,'egon','male','vip2','music,read'); Query OK, 1 row affected (0.14 sec) mysql> select * from consumer; +----------+------------------+-----------+-------------+---------------+ | id | name | sex | level | hobbies | +----------+------------------+-----------+-------------+---------------+ | 1 | egon | male | vip2 | music,read | +----------+------------------+-----------+-------------+---------------+ 1 row in set (0.00 sec) mysql> insert into consumer values -> (1,'egon','xxxxx','vip2','music,read'); #不在我範圍以內的進來就是空的了 Query OK, 1 row affected, 1 warning (0.18 sec) mysql> select * from consumer; +----------+------------------+-----------+-------------+---------------+ | id | name | sex | level | hobbies | +----------+------------------+-----------+-------------+---------------+ | 1 | egon | male | vip2 | music,read | | 1 | egon | | vip2 | music,read | +----------+------------------+-----------+-------------+---------------+ 2 rows in set (0.00 sec)
做用:用於保證數據的完整性和一致性
PRIMARY KEY (PK) 標識該字段爲該表的主鍵,能夠惟一的標識記錄
FOREIGN KEY (FK) 標識該字段爲該表的外鍵
NOT NULL 標識該字段不能爲空
UNIQUE KEY (UK) 標識該字段的值是惟一的
AUTO_INCREMENT 標識該字段的值自動增加(整數類型,並且爲主鍵)
DEFAULT 爲該字段設置默認值
UNSIGNED 無符號
ZEROFILL 使用0填充
1. 是否容許爲空,默認NULL,可設置NOT NULL,字段不容許爲空,必須賦值 2. 字段是否有默認值,缺省的默認值是NULL,若是插入記錄時不給字段賦值,此字段使用默認值 sex enum('male','female') not null default 'male' age int unsigned NOT NULL default 20 必須爲正值(無符號) 不容許爲空 默認是20 3. 是不是key 主鍵 primary key 外鍵 foreign key 索引 (index,unique...)
create table t15(
id int(11) unsigned zerofill
);
create table t16(
id int,
name char(6),
sex enum('male','female') not null default 'male' #不能爲空,若是傳空就用默認的值男
);
insert into t16(id,name) values(1,'egon');
mysql> create table t15( -> id int(11) unsigned zerofill -> ); Query OK, 0 rows affected (0.55 sec) mysql> desc t15; #Null表上顯示能夠傳空值,若是不容許,你還得給它個Default默認值 +-------+---------------------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------+---------------------------+------+-----+---------+-------+ | id | int(11) unsigned zerofill | YES | | NULL | | +-------+---------------------------+------+-----+---------+-------+ 1 row in set (0.03 sec) mysql> create table t16( -> id int, -> name char(6), -> sex enum('male','female') not null default 'male' -> ); Query OK, 0 rows affected (0.61 sec) mysql> desc t16; +-------+-----------------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------+-----------------------+------+-----+---------+-------+ | id | int(11) | YES | | NULL | | | name | char(6) | YES | | NULL | | | sex | enum('male','female') | NO | | male | | +-------+-----------------------+------+-----+---------+-------+ 3 rows in set (0.00 sec) mysql> insert into t16(id,name) values(1,'egon'); Query OK, 1 row affected (0.13 sec) mysql> select * from t16; +------+--------+------+ | id | name | sex | +------+--------+------+ | 1 | egon | male | +------+--------+------+ 1 row in set (0.00 sec)
unique key
單列惟一
#方式一 #在誰的字段後邊加unique,指的是這個字段的記錄是惟一的不能重複;
create table department(
id int unique,
name char(10) unique
);
mysql> create table department( -> id int, -> name char(10) -> ); Query OK, 0 rows affected (0.51 sec) mysql> desc department; +-------+----------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------+----------+------+-----+---------+-------+ | id | int(11) | YES | | NULL | | | name | char(10) | YES | | NULL | | +-------+----------+------+-----+---------+-------+ 2 rows in set (0.01 sec) mysql> insert into department values -> (1,'IT'), -> (2,'IT'); Query OK, 2 rows affected (0.10 sec) Records: 2 Duplicates: 0 Warnings: 0 mysql> select * from department; +------+------------+ | id | name | +------+------------+ | 1 | IT | | 2 | IT | +------+------------+ 2 rows in set (0.00 sec) mysql> drop table department; Query OK, 0 rows affected (0.39 sec) mysql> create table department( -> id int unique, -> name char(10) unique -> ); Query OK, 0 rows affected (0.99 sec) mysql> desc department; +-------+----------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------+----------+------+-----+---------+-------+ | id | int(11) | YES | UNI | NULL | | | name | char(10) | YES | UNI | NULL | | +-------+----------+------+-----+---------+-------+ 2 rows in set (0.01 sec) mysql> insert into department values -> (1,'IT'), -> (2,'IT'); ERROR 1062 (23000): Duplicate entry 'IT ' for key 'name' #報錯了說重複了
#方式二:
create table department(
id int,
name char(10),
unique(id),
unique(name)
);
insert into department values
(1,'IT'),
(2,'Sale');
mysql> drop table department; Query OK, 0 rows affected (0.33 sec) mysql> create table department( -> id int unique, -> name char(10) unique -> ); Query OK, 0 rows affected (0.73 sec) mysql> desc department; +-------+----------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------+----------+------+-----+---------+-------+ | id | int(11) | YES | UNI | NULL | | | name | char(10) | YES | UNI | NULL | | +-------+----------+------+-----+---------+-------+ 2 rows in set (0.06 sec) mysql> insert into department values -> (1,'IT'), -> (2,'Sale'); Query OK, 2 rows affected (0.12 sec) Records: 2 Duplicates: 0 Warnings: 0 mysql> select * from department; +------+------------+ | id | name | +------+------------+ | 1 | IT | | 2 | Sale | +------+------------+ 2 rows in set (0.00 sec)
聯合惟一
create table services(
id int,
ip char(15),
port int,
unique(id),
unique(ip,port) #ip和端口是惟一的,這個叫聯合惟一
);
insert into services values
(1,'192.168.11.10',80),
(2,'192.168.11.10',81),
(3,'192.168.11.13',80);
insert into services values
(4,'192.168.11.10',80);
mysql> create table services( -> id int, -> ip char(15), -> port int, -> unique(id), -> unique(ip,port) -> ); Query OK, 0 rows affected (0.75 sec) mysql> desc services; +-------+----------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------+----------+------+-----+---------+-------+ | id | int(11) | YES | UNI | NULL | | | ip | char(15) | YES | MUL | NULL | | | port | int(11) | YES | | NULL | | +-------+----------+------+-----+---------+-------+ 3 rows in set (0.06 sec) mysql> insert into services values -> (1,'192.168.11.10',80), -> (2,'192.168.11.10',81), -> (3,'192.168.11.13',80); Query OK, 3 rows affected (0.27 sec) Records: 3 Duplicates: 0 Warnings: 0 mysql> select * from services; +------+-----------------+------+ | id | ip | port | +------+-----------------+------+ | 1 | 192.168.11.10 | 80 | | 2 | 192.168.11.10 | 81 | | 3 | 192.168.11.13 | 80 | +------+-----------------+------+ 3 rows in set (0.00 sec) mysql> insert into services values -> (4,'192.168.11.10',80); ERROR 1062 (23000): Duplicate entry '192.168.11.10 -80' for key 'ip'
primary key是指約束:not null unique #不爲空且惟一
一個表中能夠:
單列作主鍵
多列作主鍵(複合主鍵)
但一個表內只能有一個主鍵primary key
存儲引擎(innodb):對於innodb存儲引擎來講,一張表內必須有一個主鍵;#innodb的獨特特性不爲空且惟一。
# 單列主鍵
create table t17(
id int primary key,
name char(16)
);
insert into t17 values
(1,'egon'),
(2,'alex');
insert into t17 values
(2,'wxx');
insert into t17(name) values
('wxx');
create table t18(
id int not null unique,
name char(16)
);
mysql> create table t17( -> id int primary key, -> name char(16) -> ); Query OK, 0 rows affected (0.71 sec) mysql> insert into t17 values -> (1,'egon'), -> (2,'alex'); Query OK, 2 rows affected (0.09 sec) Records: 2 Duplicates: 0 Warnings: 0 mysql> select * from t17; +----------+------------------+ | id | name | +----------+------------------+ | 1 | egon | | 2 | alex | +----------+------------------+ 2 rows in set (0.00 sec) mysql> select * from t17; +----------+------------------+ | id | name | +----------+------------------+ | 1 | egon | | 2 | alex | +----------+------------------+ 2 rows in set (0.00 sec) mysql> mysql> mysql> create table t18( ######若是沒有主鍵就回去自動尋找一個不爲空且惟一的字段做爲主鍵; -> id int not null unique, -> name char(16) -> ); Query OK, 0 rows affected (0.84 sec) mysql> desc t18; ###一般一個表中,都有一個ip字段用來表示它的標號,一般這個ip字段就應該設置爲它的主鍵 +-------+----------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------+----------+------+-----+---------+-------+ | id | int(11) | NO | PRI | NULL | | | name | char(16) | YES | | NULL | | +-------+----------+------+-----+---------+-------+ 2 rows in set (0.01 sec)
# 複合主鍵
create table t19(
ip char(15),
port int,
primary key(ip,port) #它倆聯合到一塊兒
);
insert into t19 values
('1.1.1.1',80),
('1.1.1.1',81);
mysql> create table t19( -> ip char(15), -> port int, -> primary key(ip,port) -> ); Query OK, 0 rows affected (0.61 sec) mysql> desc t19; +-------+----------+------+-----+-----------------+-------+ | Field | Type | Null | Key | Default | Extra | +-------+----------+------+-----+-----------------+-------+ | ip | char(15) | NO | PRI | | | | port | int(11) | NO | PRI | 0 | | +-------+----------+------+-----+-----------------+-------+ 2 rows in set (0.01 sec) mysql> insert into t19 values -> ('1.1.1.1',80), -> ('1.1.1.1',81); Query OK, 2 rows affected (0.16 sec) Records: 2 Duplicates: 0 Warnings: 0 mysql> select * from t19; +-----------------+------+ | ip | port | +-----------------+------+ | 1.1.1.1 | 80 | | 1.1.1.1 | 81 | +-----------------+------+ 2 rows in set (0.00 sec)
###auto_increment create table t20( id int primary key auto_increment, name char(16) ); insert into t20(name) values ('egon'), ('alex'), ('wxx');
insert into t20(id,name) values (7,'yuanhao'); insert into t20(name) values ('egon1'), ('egon2'), ('egon3'); #瞭解 show variables like 'auto_inc%'; ####模糊匹配 #步長: auto_increment_increment默認爲1 #起始偏移量 auto_increment_offset默認1 #設置步長 set session auto_increment_increment=5; ##只在本次連接有效 set global auto_increment_increment=5; ##設置成全局了,所有有效了 #設置起始偏移量 set global auto_increment_offset=3; 強調:起始偏移量<=步長 create table t21( id int primary key auto_increment, name char(16) ); insert into t21(name) values ('egon'), ('alex'), ('wxx'), ('yxx'); 清空表: delete from t20; ##所有都刪了;可是自增加字段的那個值沒有爲1 delete from t20 where id = 3; ##它用在刪除固定範的記錄,通常跟where連用; insert into t20(name) values ('xxx'); truncate t20; #應該用它來清空表
mysql> create table t20( -> id int primary key auto_increment, -> name char(16) -> ); Query OK, 0 rows affected (0.77 sec) mysql> desc t20; +-------+----------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------+----------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | name | char(16) | YES | | NULL | | +-------+----------+------+-----+---------+----------------+ 2 rows in set (0.08 sec) mysql> insert into t20(name)values -> ('egon'), -> ('alex'), -> ('kris'); Query OK, 3 rows affected (0.18 sec) Records: 3 Duplicates: 0 Warnings: 0 mysql> select * from t20; ##自增加 +----+------------------+ | id | name | +----+------------------+ | 1 | egon | | 2 | alex | | 3 | kris | +----+------------------+ 3 rows in set (0.00 sec) mysql> insert into t20(id,name) values #我不自增加,非要插入個7也能夠;接着下面的就會按照7自增 -> (7,'yuanhao'); Query OK, 1 row affected (0.14 sec) mysql> select * from t20; +----+------------------+ | id | name | +----+------------------+ | 1 | egon | | 2 | alex | | 3 | kris | | 7 | yuanhao | +----+------------------+ 4 rows in set (0.00 sec) mysql> insert into t20(name) values -> ('egon1'), -> ('egon2'), -> ('egon3'); Query OK, 3 rows affected (0.11 sec) Records: 3 Duplicates: 0 Warnings: 0 mysql> select * from t20; +----+------------------+ | id | name | +----+------------------+ | 1 | egon | | 2 | alex | | 3 | kris | | 7 | yuanhao | | 8 | egon1 | | 9 | egon2 | | 10 | egon3 | +----+------------------+ 7 rows in set (0.00 sec)
mysql> show variables like 'auto_inc%'; +--------------------------+-------+ | Variable_name | Value | +--------------------------+-------+ | auto_increment_increment | 1 | | auto_increment_offset | 1 | +--------------------------+-------+ 2 rows in set (0.13 sec) ##設置起始偏移量和步長。要退出exit而後從新登陸下才生效
mysql> desc t20; +-------+----------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------+----------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | name | char(16) | YES | | NULL | | +-------+----------+------+-----+---------+----------------+ 2 rows in set (0.00 sec) mysql> select * from t20; +----+------------------+ | id | name | +----+------------------+ | 1 | egon | | 2 | alex | | 3 | kris | | 7 | yuanhao | | 8 | egon1 | | 9 | egon2 | | 10 | egon3 | +----+------------------+ 7 rows in set (0.00 sec) mysql> delete from t20; #刪除記錄,但id值沒有清除掉; Query OK, 7 rows affected (0.15 sec) mysql> insert into t20(name)values -> ('xxx'); Query OK, 1 row affected (0.08 sec) mysql> select * from t20; +----+------------------+ | id | name | +----+------------------+ | 11 | xxx | +----+------------------+ 1 row in set (0.00 sec) mysql> truncate t20; #id值也就被清除了。 Query OK, 0 rows affected (0.59 sec) mysql> insert into t20(name)values -> ('xxx'); Query OK, 1 row affected (0.12 sec) mysql> select * from t20; +----+------------------+ | id | name | +----+------------------+ | 1 | xxx | +----+------------------+ 1 row in set (0.00 sec)
foreign key:創建表之間的關係
#一、創建表關係:
#先建被關聯的表,而且保證被關聯的字段惟一
create table dep(
id int primary key, ##應該保證它的惟一性,設置爲主鍵
name char(16),
comment char(50)
);
#再創建關聯的表
create table emp(
id int primary key,
name char(10),
sex enum('male','female'),
dep_id int,
foreign key(dep_id) references dep(id) #關聯另一張表的部門列
on delete cascade ########刪除重複,只要被關聯的表移動,關聯的表也跟着移動
on update cascade ######更新重複,
);
mysql> create table dep( -> id int primary key, -> name char(16), -> comment char(50) -> ); Query OK, 0 rows affected (0.65 sec) mysql> desc dep; +---------+----------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +---------+----------+------+-----+---------+-------+ | id | int(11) | NO | PRI | NULL | | | name | char(16) | YES | | NULL | | | comment | char(50) | YES | | NULL | | +---------+----------+------+-----+---------+-------+ 3 rows in set (0.02 sec) mysql> mysql> create table emp( -> id int primary key, -> name char(10), -> sex enum('male','female'), -> dep_id int, -> foreign key(dep_id) references dep(id)); Query OK, 0 rows affected (1.59 sec) mysql> desc emp; ##已經關聯了,dep_id +--------+-----------------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +--------+-----------------------+------+-----+---------+-------+ | id | int(11) | NO | PRI | NULL | | | name | char(10) | YES | | NULL | | | sex | enum('male','female') | YES | | NULL | | | dep_id | int(11) | YES | MUL | NULL | | +--------+-----------------------+------+-----+---------+-------+ 4 rows in set (0.08 sec) mysql> insert into dep values -> (1,"IT","技術能力有限部門"), -> (2,"銷售","銷售能力不足部門"), -> (3,"財務","花錢特別多部門"); Query OK, 3 rows affected (0.13 sec) Records: 3 Duplicates: 0 Warnings: 0 mysql> insert into emp values -> (1,'egon','male',1); Query OK, 1 row affected (0.19 sec) mysql> insert into emp values -> (2,'alex','male',1), -> (3,'wupeiqi','female',2), -> (4,'yuanhao','male',3), -> (5,'jinximn','male',2); Query OK, 4 rows affected (0.06 sec) Records: 4 Duplicates: 0 Warnings: 0 mysql> select * from emp; +----+------------+--------+--------+ | id | name | sex | dep_id | +----+------------+--------+--------+ | 1 | egon | male | 1 | | 2 | alex | male | 1 | | 3 | wupeiqi | female | 2 | | 4 | yuanhao | male | 3 | | 5 | jinximn | male | 2 | +----+------------+--------+--------+ 5 rows in set (0.00 sec) mysql> select * from dep; +----+----------------------+--------------------------------------------------------------------+ | id | name | comment | +----+----------------------+--------------------------------------------------------------------+ | 1 | IT | 技術能力有限部門| | 2 | 銷售 | 銷售能力不足部門| | 3 | 財務 | 花錢特別多部門| +----+----------------------+--------------------------------------------------------------------+ 3 rows in set (0.00 sec) mysql> mysql> delete from emp where dep_id=1; Query OK, 2 rows affected (0.23 sec) mysql> delete from dep where id=1; Query OK, 1 row affected (0.08 sec) mysql> select * from emp; +----+------------+--------+--------+ | id | name | sex | dep_id | +----+------------+--------+--------+ | 3 | wupeiqi | female | 2 | | 4 | yuanhao | male | 3 | | 5 | jinximn | male | 2 | +----+------------+--------+--------+ 3 rows in set (0.00 sec) mysql> select * from dep; +----+----------------------+--------------------------------------------------------------------+ | id | name | comment| +----+----------------------+--------------------------------------------------------------------+ | 2 | 銷售 | 銷售能力不足部門| | 3 | 財務 | 花錢特別多部門| +----+----------------------+--------------------------------------------------------------------+ 2 rows in set (0.00 sec) mysql> delete from dep where id=3; #刪不掉,由於它們有關聯關係 ERROR 1451 (23000): Cannot delete or update a parent row: a foreign key constrai nt fails (`db4`.`emp`, CONSTRAINT `emp_ibfk_1` FOREIGN KEY (`dep_id`) REFERENCES `dep` (`id`))
#二、插入數據
#先往被關聯表插入記錄
insert into dep values
(1,"IT","技術能力有限部門"),
(2,"銷售","銷售能力不足部門"),
(3,"財務","花錢特別多部門");
#再往關聯表插入記錄
insert into emp values
(1,'egon','male',1);
insert into emp values
(2,'alex','male',1),
(3,'wupeiqi','female',2),
(4,'yuanhao','male',3),
(5,'jinximn','male',2);
delete from emp where dep_id=1;
delete from dep where id=1;
delete from dep where id=3;
mysql> drop table emp; Query OK, 0 rows affected (0.32 sec) mysql> drop table dep; Query OK, 0 rows affected (0.25 sec) mysql> create table dep( -> id int primary key, -> name char(16), -> comment char(50) -> ); Query OK, 0 rows affected (0.66 sec) mysql> create table emp( -> id int primary key, -> name char(10), -> sex enum('male','female'), -> dep_id int, -> foreign key(dep_id) references dep(id) -> on delete cascade -> on update cascade -> ); Query OK, 0 rows affected (0.74 sec) mysql> insert into dep values -> (1,"IT","技術能力有限部門"), -> (2,"銷售","銷售能力不足部門"), -> (3,"財務","花錢特別多部門"); Query OK, 3 rows affected (0.14 sec) Records: 3 Duplicates: 0 Warnings: 0 mysql> insert into emp values -> (1,'egon','male',1); Query OK, 1 row affected (0.17 sec) mysql> mysql> insert into emp values -> (2,'alex','male',1), -> (3,'wupeiqi','female',2), -> (4,'yuanhao','male',3), -> (5,'jinximn','male',2); Query OK, 4 rows affected (0.09 sec) Records: 4 Duplicates: 0 Warnings: 0 mysql> select * from dep; +----+----------------------+--------------------------------------------------------------------+ | id | name | comment| +----+----------------------+--------------------------------------------------------------------+ | 1 | IT | 技術能力有限部門| | 2 | 銷售 | 銷售能力不足部門| | 3 | 財務 | 花錢特別多部門| +----+----------------------+--------------------------------------------------------------------+ 3 rows in set (0.00 sec) mysql> select * from emp; +----+------------+--------+--------+ | id | name | sex | dep_id | +----+------------+--------+--------+ | 1 | egon | male | 1 | | 2 | alex | male | 1 | | 3 | wupeiqi | female | 2 | | 4 | yuanhao | male | 3 | | 5 | jinximn | male | 2 | +----+------------+--------+--------+ 5 rows in set (0.00 sec) mysql> delete from dep where id=1; Query OK, 1 row affected (0.11 sec) mysql> select * from dep; +----+----------------------+--------------------------------------------------------------------+ | id | name | comment| +----+----------------------+--------------------------------------------------------------------+ | 2 | 銷售 | 銷售能力不足部門| | 3 | 財務 | 花錢特別多部門| +----+----------------------+--------------------------------------------------------------------+ 2 rows in set (0.00 sec) mysql> select * from emp; +----+------------+--------+--------+ | id | name | sex | dep_id | +----+------------+--------+--------+ | 3 | wupeiqi | female | 2 | | 4 | yuanhao | male | 3 | | 5 | jinximn | male | 2 | +----+------------+--------+--------+ 3 rows in set (0.00 sec) mysql> update dep set id=202 where id=2; Query OK, 1 row affected (0.10 sec) Rows matched: 1 Changed: 1 Warnings: 0 mysql> select * from dep; +-----+----------------------+--------------------------------------------------------------------+ | id | name | comment| +-----+----------------------+--------------------------------------------------------------------+ | 3 | 財務 | 花錢特別多部門| | 202 | 銷售 | 銷售能力不足部門| +-----+----------------------+--------------------------------------------------------------------+ 2 rows in set (0.00 sec) mysql> select * from emp; +----+------------+--------+--------+ | id | name | sex | dep_id | +----+------------+--------+--------+ | 3 | wupeiqi | female | 202 | | 4 | yuanhao | male | 3 | | 5 | jinximn | male | 202 | +----+------------+--------+--------+ 3 rows in set (0.00 sec)
最好不要直接把表建好硬性關係;先從邏輯上實現兩張表的關係;從應用程序層面去搞,不要把兩張表耦合到一塊兒;少擴散數據庫,在應用程序層面
兩張表之間的關係: 1、多對一 出版社 書(foreign key(press_id) references press(id)) 2、多對多 做者 書 egon: 九陽神功 九陰真經 alex: 九陽神功 葵花寶典 yuanhao: 獨孤九劍 降龍十巴掌 葵花寶典 wpq: 九陽神功 insert into author2book(author_id,book_id) values (1,1), (1,2), (2,1), (2,6); 3、一對一 customer表 student表
多對一
竅門:先站左表找右邊多對一,再站右表找多對一左表的關係;
mysql> use db4; Database changed mysql> create table press( -> id int primary key auto_increment, -> name varchar(20) -> ); Query OK, 0 rows affected (1.23 sec) mysql> 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 -> ); Query OK, 0 rows affected (0.76 sec) mysql> insert into press(name) values -> ('北京工業地雷出版社'), -> ('人民音樂很差聽出版社'), -> ('知識產權沒有用出版社') -> ; Query OK, 3 rows affected (0.13 sec) Records: 3 Duplicates: 0 Warnings: 0 mysql> insert into book(name,press_id) values -> ('九陽神功',1), -> ('九陰真經',2), -> ('九陰白骨爪',2), -> ('獨孤九劍',3), -> ('降龍十巴掌',2), -> ('葵花寶典',3) -> ; Query OK, 6 rows affected (0.09 sec) Records: 6 Duplicates: 0 Warnings: 0 mysql> select * from press; +----+--------------------------------+ | id | name | +----+--------------------------------+ | 1 | 北京工業地雷出版社 | | 2 | 人民音樂很差聽出版社 | | 3 | 知識產權沒有用出版社 | +----+--------------------------------+ 3 rows in set (0.08 sec) mysql> select * from book; +----+-----------------+----------+ | id | name | press_id | +----+-----------------+----------+ | 1 | 九陽神功 | 1 | | 2 | 九陰真經 | 2 | | 3 | 九陰白骨爪 | 2 | | 4 | 獨孤九劍 | 3 | | 5 | 降龍十巴掌 | 2 | | 6 | 葵花寶典 | 3 | +----+-----------------+----------+ 6 rows in set (0.00 sec)
多對多
站在左表多對一,站在右表多對一;把關係獨立出來單獨列一個表,有一個字段關聯左表,又有一個字段關聯右表;
egon:
九陽神功
九陰真經
alex:
九陽神功
葵花寶典
yuanhao:
獨孤九劍
降龍十巴掌
葵花寶典
wpq:
九陽神功
insert into author2book(author_id,book_id) values
(1,1), (1,2), (2,1), (2,6);
mysql> create table author( -> id int primary key auto_increment, -> name varchar(20) -> ); Query OK, 0 rows affected (0.91 sec) mysql> 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) -> ); Query OK, 0 rows affected (1.19 sec) mysql> insert into author(name) values('egon'),('alex'),('yuanhao'),('wpq'); Query OK, 4 rows affected (0.22 sec) Records: 4 Duplicates: 0 Warnings: 0 mysql> select * from author; +----+---------+ | id | name | +----+---------+ | 1 | egon | | 2 | alex | | 3 | yuanhao | | 4 | wpq | +----+---------+ 4 rows in set (0.00 sec) mysql> select * from book; +----+-----------------+----------+ | id | name | press_id | +----+-----------------+----------+ | 1 | 九陽神功 | 1 | | 2 | 九陰真經 | 2 | | 3 | 九陰白骨爪 | 2 | | 4 | 獨孤九劍 | 3 | | 5 | 降龍十巴掌 | 2 | | 6 | 葵花寶典 | 3 | +----+-----------------+----------+ 6 rows in set (0.00 sec) mysql> insert into author2book(author_id,book_id) values -> (1,1), -> (1,2), -> (2,1), -> (2,6); Query OK, 4 rows affected (0.18 sec) Records: 4 Duplicates: 0 Warnings: 0 mysql> select * from author2book; +----+-----------+---------+ | id | author_id | book_id | +----+-----------+---------+ | 1 | 1 | 1 | | 2 | 1 | 2 | | 3 | 2 | 1 | | 4 | 2 | 6 | +----+-----------+---------+ 4 rows in set (0.00 sec)
一對一
在後有記錄的那個字段加個foreign key
mysql> create database db5; Query OK, 1 row affected (0.22 sec) mysql> use db5; Database changed mysql> create table customer( -> id int primary key auto_increment, -> name varchar(20) not null, -> qq varchar(10) not null, -> phone char(16) not null -> ); Query OK, 0 rows affected (0.88 sec) mysql> 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 -> ); Query OK, 0 rows affected (1.40 sec) mysql> insert into customer(name,qq,phone) values -> ('李飛機','31811231',13811341220), -> ('王大炮','123123123',15213146809), -> ('守榴彈','283818181',1867141331), -> ('吳坦克','283818181',1851143312), -> ('贏火箭','888818181',1861243314), -> ('戰地雷','112312312',18811431230) -> ; Query OK, 6 rows affected (0.17 sec) Records: 6 Duplicates: 0 Warnings: 0 mysql> insert into student(class_name,customer_id) values -> ('脫產3班',3), -> ('週末19期',4), -> ('週末19期',5) -> ; Query OK, 3 rows affected (0.14 sec) Records: 3 Duplicates: 0 Warnings: 0 mysql> select * from customer; +----+-----------+-----------+-------------+ | id | name | qq | phone | +----+-----------+-----------+-------------+ | 1 | 李飛機 | 31811231 | 13811341220 | | 2 | 王大炮 | 123123123 | 15213146809 | | 3 | 守榴彈 | 283818181 | 1867141331 | | 4 | 吳坦克 | 283818181 | 1851143312 | | 5 | 贏火箭 | 888818181 | 1861243314 | | 6 | 戰地雷 | 112312312 | 18811431230 | +----+-----------+-----------+-------------+ 6 rows in set (0.00 sec) mysql> select * from student; +----+-------------+-------------+ | id | class_name | customer_id | +----+-------------+-------------+ | 1 | 脫產3班 | 3 | | 2 | 週末19期 | 4 | | 3 | 週末19期 | 5 | +----+-------------+-------------+ 3 rows in set (0.00 sec)