第四模塊:網絡編程進階&數據庫開發 第2章·MySQL數據庫開發

  • 01-MySQL開篇
  • 02-MySQL簡單介紹
  • 03-不一樣平臺下安裝MySQL
  • 04-Windows平臺MySQL密碼設置與破解
  • 05-Linux平臺MySQL密碼設置與破解
  • 06-Mac平臺MySQL密碼設置與破解
  • 07-統一字符編碼
  • 08-初識SQL語句
  • 09-庫操做
  • 10-存儲引擎介紹
  • 11-表的增刪改查
  • 12-整數類型
  • 13-日期類型
  • 14-字符類型
  • 15-枚舉類型與集合類型
  • 16-約束條件not null與default
  • 17-約束條件unique key
  • 18-約束條件promary key
  • 19-約束條件auto_increment
  • 20-約束條件之foreign key
  • 21-表關係之多對一
  • 22-表關係之多對多
  • 23-表關係之一對一
  • 24-記錄的增刪改查
  • 25-簡單查詢
  • 26-where約束
  • 27-group by分組
  • 28-having過濾
  • 29-order by排序
  • 30-limit限制條數
  • 31-單表查詢的語法順序與執行順序總結
  • 32-正則查詢
  • 33-連表操做
  • 34-select語句關鍵字執行優先級
  • 35-子查詢
  • 36-多表查詢練習
  • 37-權限管理
  • 38-Navicat工具的使用
  • 39-pymysql模塊之基本使用
  • 40-pymysql模塊之sql注入
  • 41-pymysql模塊之增刪改查
  • 42-MySQL內置功能介紹
  • 43-視圖
  • 44-觸發器
  • 45-存儲過程
  • 46-應用程序與數據庫結合使用的三種方式
  • 47-事務
  • 48-函數與流程控制
  • 49-索引原理

01-MySQL開篇

一、再也不直接進行文件操做;

二、MySQL數據庫管理軟件本質是C/S架構的socket;

三、使用別人的軟件,按照數據庫的規範進行,即引出SQL語句(structure query language)

02-MySQL簡單介紹

一、數據庫相關概念初識;

1)數據庫服務器:一臺計算機,用途很是專注,運行數據庫管理軟件(MySQL、Oracle、OceanBase)的計算機;css

2)數據庫管理軟件:MySQL、Oracle、SQLServer、MariaDB、DB二、SQLite;html

3)庫:文件夾,咱們組織文件的方式不該該放在同一個文件夾,而應該經過文件夾規範、層級、劃分區域地進行管理;java

4)表:文件,相似於Excel表;node

5)記錄:事物一系列典型的特徵,好比age、name、sex、from、hobby、tel、position;python

6)數據:描述事物特徵的符號;mysql

二、MySQL介紹

  MySQL是一個關係型數據庫管理系統,由瑞典MySQL AB 公司開發,目前屬於 Oracle 旗下公司。MySQL 最流行的關係型數據庫管理系統,在 WEB 應用方面MySQL是最好的 RDBMS (Relational Database Management System,關係數據庫管理系統) 應用軟件之一。linux

1)MySQL是什麼?正則表達式

mysql就是一個基於socket編寫的C/S架構的軟件;
客戶端軟件
  mysql自帶:如mysql命令,mysqldump命令等;
  python模塊:如pymysql;

2)數據庫管理軟件分類sql

  • 關係型(SQL):MySQL、Oracle、DB二、SQLServer
  • 非關係型(No SQL-not only sql):Redis、Memcache、MongoDB

03-不一樣平臺下安裝MySQL

一、Windows平臺安裝教程;

1)下載連接:數據庫

msi版本:https://cdn.mysql.com//Downloads/MySQLInstaller/mysql-installer-community-5.7.22.1.msi (推薦使用)

zip免安裝版本:https://cdn.mysql.com/archives/mysql-5.7/mysql-5.7.21-winx64.zip

2)安裝教程:

https://www.linuxidc.com/Linux/2017-11/148521.htm?hmsr=toutiao.io

https://www.2cto.com/database/201803/732822.html

 二、Linux平臺下安裝教程;

http://www.javashuo.com/article/p-mmjxepcq-k.html

04-Windows平臺MySQL密碼設置與破解

一、參考博文;

http://www.javashuo.com/article/p-zxuckyyl-bb.html

https://www.2cto.com/database/201803/732822.html

05-Linux平臺MySQL密碼設置與破解

一、CentOS7下,忘記MySQL密碼的修改方式教程:

http://www.javashuo.com/article/p-rkdcqswc-be.html

06-Mac平臺MySQL密碼設置與破解

一、MacOS平臺下破解密碼的方式;

07-統一字符編碼

強調:配置文件中的註釋能夠有中文,可是配置項中不能出現中文;

一、Windows平臺下(MySQL5.7在Windows平臺下,默認就是統一爲utf8):

 

二、Linux平臺下;

 解決辦法:

一、先備份my.cnf文件;

cp -a /etc/my.cnf{,.ori}

二、添加記錄;

vim /etc/my.cnf
# For advice on how to change settings please see
# http://dev.mysql.com/doc/refman/5.7/en/server-configuration-defaults.html

[mysqld]
#
# 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
#
# 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
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock

# Disabling symbolic-links is recommended to prevent assorted security risks
symbolic-links=0

log-error=/var/log/mysqld.log
pid-file=/var/run/mysqld/mysqld.pid
character_set_server=utf8

三、重啓mysqld服務;

systemctl restart mysqld
systemctl status mysqld

四、進行驗證;

[root@iZ2ze2m3z176dpbiaolifiZ ~]# mysql -uroot -p -hlocalhost -P 3306
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 3
Server version: 5.7.22 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.7.22, for Linux (x86_64) using  EditLine wrapper

Connection id:        3
Current database:    
Current user:        root@localhost
SSL:            Not in use
Current pager:        stdout
Using outfile:        ''
Using delimiter:    ;
Server version:        5.7.22 MySQL Community Server (GPL)
Protocol version:    10
Connection:        Localhost via UNIX socket
Server characterset:    utf8
Db     characterset:    utf8
Client characterset:    utf8
Conn.  characterset:    utf8
UNIX socket:        /var/lib/mysql/mysql.sock
Uptime:            35 sec

Threads: 1  Questions: 15  Slow queries: 0  Opens: 105  Flush tables: 1  Open tables: 98  Queries per second avg: 0.428
--------------

mysql> 

三、MacOS平臺;

參考博文:https://www.jb51.net/article/136343.htm

08-初識SQL語句

一、操做文件夾(庫);

1)增;

建立數據庫:

create database 數據庫名(Luffycity) charset utf8;

本質是在數據庫的data目錄下,建立一個名稱爲「數據庫名」的文件夾;

2)查;

在建立的前面加上關鍵字show:

show create database 數據庫名(luffycity);

3)改(沒有數據庫更名那麼一說);

alter database 數據庫名(luffycity) charset gbk;

4)刪;

drop database 數據庫名(luffycity);
show databases;

PS:在Windows平臺下,使用.msi安裝的數據庫的數據存儲目錄以下:

C:\ProgramData\MySQL\MySQL Server 5.7\Data

二、操做文件(表);

1)首先要有這個文件夾(即數據庫名);

2)本質是切換文件夾;

use 數據庫名(luffycity);

3)查看當前所在文件夾;

select database();

4)新增一個表(文件);

create table 表名(userinfo)(id int,
name char
);

5)查詢表;

show create table userinfo;
show tables;

6)改表結構;

alter table userinfo modify name char(30);
show create table userinfo;
alter table userinfo change name NAME char(7);

7) 查看錶結構;

desc userinfo;

8) 刪除表;

drop table userinfo;

三、操做文件內容(記錄);

1)增;

insert into userinfo(id,name) values(1,'cuixiaozhao'),(2,'lijingping'),(3,'cuitianqing');

2)查;

select id,name from luffycity.userinfo;
select * from luffycity.userinfo#不推薦使用通配符*;

3)改

update luffycity.userinfo set name = '天晴天朗' where id =1;
update luffycity.userinfo set name = 'PythonFullStack';

4)刪

delete from userinfo;
delete from userinfo where id =3;

操做日誌:

Enter password: ************
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 20
Server version: 5.7.20-log MySQL Community Server (GPL)

Copyright (c) 2000, 2017, 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> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sakila             |
| sys                |
| world              |
+--------------------+
6 rows in set (0.00 sec)

mysql> create database luffycity charset utf8;
Query OK, 1 row affected (0.00 sec)

mysql> show create database luffycity;
+-----------+--------------------------------------------------------------------+
| Database  | Create Database                                                    |
+-----------+--------------------------------------------------------------------+
| luffycity | CREATE DATABASE `luffycity` /*!40100 DEFAULT CHARACTER SET utf8 */ |
+-----------+--------------------------------------------------------------------+
1 row in set (0.00 sec)

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| luffycity          |
| mysql              |
| performance_schema |
| sakila             |
| sys                |
| world              |
+--------------------+
7 rows in set (0.00 sec)

mysql> use luffycity;
Database changed
mysql> select database();
+------------+
| database() |
+------------+
| luffycity  |
+------------+
1 row in set (0.00 sec)

mysql> create table userinfo(id int,name char);
Query OK, 0 rows affected (0.01 sec)

mysql> show create table userinfo;
+----------+---------------------------------------------------------------------------------------------------------------------------+
| Table    | Create Table                                                                                                              |
+----------+---------------------------------------------------------------------------------------------------------------------------+
| userinfo | CREATE TABLE `userinfo` (
  `id` int(11) DEFAULT NULL,
  `name` char(1) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 |
+----------+---------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.01 sec)

mysql> show tables;
+---------------------+
| Tables_in_luffycity |
+---------------------+
| userinfo            |
+---------------------+
1 row in set (0.00 sec)

mysql> desc userinfo;
+-------+---------+------+-----+---------+-------+
| Field | Type    | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| id    | int(11) | YES  |     | NULL    |       |
| name  | char(1) | YES  |     | NULL    |       |
+-------+---------+------+-----+---------+-------+
2 rows in set (0.00 sec)

mysql> alter table userinfo modify name char(11);
Query OK, 0 rows affected (0.04 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> desc userinfo;
+-------+----------+------+-----+---------+-------+
| Field | Type     | Null | Key | Default | Extra |
+-------+----------+------+-----+---------+-------+
| id    | int(11)  | YES  |     | NULL    |       |
| name  | char(11) | YES  |     | NULL    |       |
+-------+----------+------+-----+---------+-------+
2 rows in set (0.00 sec)

mysql> alter table userinfo change name NAME char(7);
Query OK, 0 rows affected (0.03 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> desc userinfo;
+-------+---------+------+-----+---------+-------+
| Field | Type    | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| id    | int(11) | YES  |     | NULL    |       |
| NAME  | char(7) | YES  |     | NULL    |       |
+-------+---------+------+-----+---------+-------+
2 rows in set (0.00 sec)

mysql> drop table userinfo;
Query OK, 0 rows affected (0.01 sec)

mysql> show tables;
Empty set (0.00 sec)

mysql> create table userinfo(id int,name char);
Query OK, 0 rows affected (0.01 sec)

mysql> show tables;
+---------------------+
| Tables_in_luffycity |
+---------------------+
| userinfo            |
+---------------------+
1 row in set (0.00 sec)

mysql> desc userinfo;
+-------+---------+------+-----+---------+-------+
| Field | Type    | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| id    | int(11) | YES  |     | NULL    |       |
| name  | char(1) | YES  |     | NULL    |       |
+-------+---------+------+-----+---------+-------+
2 rows in set (0.00 sec)

mysql> insert into userinfo(id,name) values(1,'cuixiaozhao'),(2,'lijingping'),(3,'cuitianqing');
ERROR 1406 (22001): Data too long for column 'name' at row 1
mysql> alter table userinfo modify name char(30);
Query OK, 0 rows affected (0.03 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> desc userinfo;
+-------+----------+------+-----+---------+-------+
| Field | Type     | Null | Key | Default | Extra |
+-------+----------+------+-----+---------+-------+
| id    | int(11)  | YES  |     | NULL    |       |
| name  | char(30) | YES  |     | NULL    |       |
+-------+----------+------+-----+---------+-------+
2 rows in set (0.00 sec)

mysql> insert into userinfo(id,name) values(1,'cuixiaozhao'),(2,'lijingping'),(3,'cuitianqing');
Query OK, 3 rows affected (0.00 sec)
Records: 3  Duplicates: 0  Warnings: 0

mysql> select id,name from userinfo;
+------+-------------+
| id   | name        |
+------+-------------+
|    1 | cuixiaozhao |
|    2 | lijingping  |
|    3 | cuitianqing |
+------+-------------+
3 rows in set (0.00 sec)

mysql> select id,name from luffycity.userinfo;
+------+-------------+
| id   | name        |
+------+-------------+
|    1 | cuixiaozhao |
|    2 | lijingping  |
|    3 | cuitianqing |
+------+-------------+
3 rows in set (0.00 sec)

mysql> select * from luffycity.userinfo;
+------+-------------+
| id   | name        |
+------+-------------+
|    1 | cuixiaozhao |
|    2 | lijingping  |
|    3 | cuitianqing |
+------+-------------+
3 rows in set (0.00 sec)

mysql> select * from userinfo;
+------+-------------+
| id   | name        |
+------+-------------+
|    1 | cuixiaozhao |
|    2 | lijingping  |
|    3 | cuitianqing |
+------+-------------+
3 rows in set (0.00 sec)

mysql> desc userinfo;
+-------+----------+------+-----+---------+-------+
| Field | Type     | Null | Key | Default | Extra |
+-------+----------+------+-----+---------+-------+
| id    | int(11)  | YES  |     | NULL    |       |
| name  | char(30) | YES  |     | NULL    |       |
+-------+----------+------+-----+---------+-------+
2 rows in set (0.00 sec)

mysql> select * from userinfo;
+------+-------------+
| id   | name        |
+------+-------------+
|    1 | cuixiaozhao |
|    2 | lijingping  |
|    3 | cuitianqing |
+------+-------------+
3 rows in set (0.00 sec)

mysql> update luffycity.userinfo set name = '天晴天朗' where id = 1;
Query OK, 1 row affected (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> update luffycity.userinfo set name = '小可愛·李靜瓶' where id = 2;
Query OK, 1 row affected (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> select id,name from userinfo;
+------+----------------------+
| id   | name                 |
+------+----------------------+
|    1 | 天晴天朗             |
|    2 | 小可愛·李靜瓶        |
|    3 | cuitianqing          |
+------+----------------------+
3 rows in set (0.00 sec)

mysql> select name,id from userinfo;
+----------------------+------+
| name                 | id   |
+----------------------+------+
| 天晴天朗             |    1 |
| 小可愛·李靜瓶        |    2 |
| cuitianqing          |    3 |
+----------------------+------+
3 rows in set (0.00 sec)

mysql> update luffycity.userinfo set name = 'PythonFullstack';
Query OK, 3 rows affected (0.07 sec)
Rows matched: 3  Changed: 3  Warnings: 0

mysql> select * from userinfo;
+------+-----------------+
| id   | name            |
+------+-----------------+
|    1 | PythonFullstack |
|    2 | PythonFullstack |
|    3 | PythonFullstack |
+------+-----------------+
3 rows in set (0.00 sec)

mysql> delete from userinfo where id = 1;
Query OK, 1 row affected (0.00 sec)

mysql> select * from userinfo;
+------+-----------------+
| id   | name            |
+------+-----------------+
|    2 | PythonFullstack |
|    3 | PythonFullstack |
+------+-----------------+
2 rows in set (0.00 sec)

mysql> delete from userinfo where id = 3;
Query OK, 1 row affected (0.00 sec)

mysql> delete from userinfo where id = 33;
Query OK, 0 rows affected (0.00 sec)

mysql> select * from userinfo;
+------+-----------------+
| id   | name            |
+------+-----------------+
|    2 | PythonFullstack |
+------+-----------------+
1 row in set (0.00 sec)

mysql> delete from userinfo;
Query OK, 1 row affected (0.00 sec)

mysql> show create table userinfo;
+----------+----------------------------------------------------------------------------------------------------------------------------+
| Table    | Create Table                                                                                                               |
+----------+----------------------------------------------------------------------------------------------------------------------------+
| userinfo | CREATE TABLE `userinfo` (
  `id` int(11) DEFAULT NULL,
  `name` char(30) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 |
+----------+----------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

mysql> show tables;
+---------------------+
| Tables_in_luffycity |
+---------------------+
| userinfo            |
+---------------------+
1 row in set (0.00 sec)

mysql>

09-庫操做

一、SQL語句;

  對數據庫進行查詢和修改的操做語言叫作SQL。SQL的含義是「結構化查詢語言」-structured Query Language。

  SQL包含以下4個部分:

  • 數據定義語言(DDL):DROP 、CREATE 、ALTER等語句;
  • 數據操做語言(DML):INSERT(插入)、 UPDATE(修改)、 DELETE(刪除)等語句;
  • 數據查詢語言(DQL):SELECT語句;
  • 數據控制語言(DCL):GRANT、 REVOKE 、COMMIT、 RELLBACK等語句;

二、系統數據庫介紹;

  • mysql
  • performance_schema
  • sakila
  • sys
  • world

博文參考:http://www.javashuo.com/article/p-vbepxihz-ep.html

三、建立數據庫;

1)語法;

CREATE DATABASE luffycity CHARSET utf8;

2)數據名的命名規則;

  • 能夠由字母、數字、下劃線、@、#、$但不推薦使用呢!;
  • 區分大小寫;
  • 惟一性;
  • 不能使用關鍵字如 create select;
  • 不能單獨使用數字;
  • 最長128位;

博文參考:https://blog.csdn.net/java_mdzy/article/details/75304297

3)數據庫操做;

  • 查看數據庫
  • show databases;
  • show create database db1;
  • select database();
  • 選擇數據庫
  • USE 數據庫名
  • 刪除數據庫
  • DROP DATABASE 數據庫名;
  • 修改數據庫
  • alter database db1 charset utf8;

4)數據庫幫助help;

Enter password: ************
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 21
Server version: 5.7.20-log MySQL Community Server (GPL)

Copyright (c) 2000, 2017, 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> help

For information about MySQL products and services, visit:
   http://www.mysql.com/
For developer information, including the MySQL Reference Manual, visit:
   http://dev.mysql.com/
To buy MySQL Enterprise support, training, or other products, visit:
   https://shop.mysql.com/

List of all MySQL commands:
Note that all text commands must be first on line and end with ';'
?         (\?) Synonym for `help'.
clear     (\c) Clear the current input statement.
connect   (\r) Reconnect to the server. Optional arguments are db and host.
delimiter (\d) Set statement delimiter.
ego       (\G) Send command to mysql server, display result vertically.
exit      (\q) Exit mysql. Same as quit.
go        (\g) Send command to mysql server.
help      (\h) Display this help.
notee     (\t) Don't write into outfile.
print     (\p) Print current command.
prompt    (\R) Change your mysql prompt.
quit      (\q) Quit mysql.
rehash    (\#) Rebuild completion hash.
source    (\.) Execute an SQL script file. Takes a file name as an argument.
status    (\s) Get status information from the server.
tee       (\T) Set outfile [to_outfile]. Append everything into given outfile.
use       (\u) Use another database. Takes database name as argument.
charset   (\C) Switch to another charset. Might be needed for processing binlog with multi-byte charsets.
warnings  (\W) Show warnings after every statement.
nowarning (\w) Don't show warnings after every statement.
resetconnection(\x) Clean session context.

For server side help, type 'help contents'

mysql> \h

For information about MySQL products and services, visit:
   http://www.mysql.com/
For developer information, including the MySQL Reference Manual, visit:
   http://dev.mysql.com/
To buy MySQL Enterprise support, training, or other products, visit:
   https://shop.mysql.com/

List of all MySQL commands:
Note that all text commands must be first on line and end with ';'
?         (\?) Synonym for `help'.
clear     (\c) Clear the current input statement.
connect   (\r) Reconnect to the server. Optional arguments are db and host.
delimiter (\d) Set statement delimiter.
ego       (\G) Send command to mysql server, display result vertically.
exit      (\q) Exit mysql. Same as quit.
go        (\g) Send command to mysql server.
help      (\h) Display this help.
notee     (\t) Don't write into outfile.
print     (\p) Print current command.
prompt    (\R) Change your mysql prompt.
quit      (\q) Quit mysql.
rehash    (\#) Rebuild completion hash.
source    (\.) Execute an SQL script file. Takes a file name as an argument.
status    (\s) Get status information from the server.
tee       (\T) Set outfile [to_outfile]. Append everything into given outfile.
use       (\u) Use another database. Takes database name as argument.
charset   (\C) Switch to another charset. Might be needed for processing binlog with multi-byte charsets.
warnings  (\W) Show warnings after every statement.
nowarning (\w) Don't show warnings after every statement.
resetconnection(\x) Clean session context.

For server side help, type 'help contents'

mysql> \c
mysql> help create;
Many help items for your request exist.
To make a more specific request, please type 'help <item>',
where <item> is one of the following
topics:
   CREATE DATABASE
   CREATE EVENT
   CREATE FUNCTION
   CREATE FUNCTION UDF
   CREATE INDEX
   CREATE LOGFILE GROUP
   CREATE PROCEDURE
   CREATE SERVER
   CREATE TABLE
   CREATE TABLESPACE
   CREATE TRIGGER
   CREATE USER
   CREATE VIEW
   SHOW
   SHOW CREATE DATABASE
   SHOW CREATE EVENT
   SHOW CREATE FUNCTION
   SHOW CREATE PROCEDURE
   SHOW CREATE TABLE
   SHOW CREATE USER
   SPATIAL

mysql> help use;
Name: 'USE'
Description:
Syntax:
USE db_name

The USE db_name statement tells MySQL to use the db_name database as
the default (current) database for subsequent statements. The database
remains the default until the end of the session or another USE
statement is issued:

USE db1;
SELECT COUNT(*) FROM mytable;   # selects from db1.mytable
USE db2;
SELECT COUNT(*) FROM mytable;   # selects from db2.mytable

URL: http://dev.mysql.com/doc/refman/5.7/en/use.html


mysql> help insert;
Name: 'INSERT'
Description:
Syntax:
INSERT [LOW_PRIORITY | DELAYED | HIGH_PRIORITY] [IGNORE]
    [INTO] tbl_name
    [PARTITION (partition_name [, partition_name] ...)]
    [(col_name [, col_name] ...)]
    {VALUES | VALUE} (value_list) [, (value_list)] ...
    [ON DUPLICATE KEY UPDATE assignment_list]

INSERT [LOW_PRIORITY | DELAYED | HIGH_PRIORITY] [IGNORE]
    [INTO] tbl_name
    [PARTITION (partition_name [, partition_name] ...)]
    SET assignment_list
    [ON DUPLICATE KEY UPDATE assignment_list]

INSERT [LOW_PRIORITY | HIGH_PRIORITY] [IGNORE]
    [INTO] tbl_name
    [PARTITION (partition_name [, partition_name] ...)]
    [(col_name [, col_name] ...)]
    SELECT ...
    [ON DUPLICATE KEY UPDATE assignment_list]

value:
    {expr | DEFAULT}

value_list:
    value [, value] ...

assignment:
    col_name = value

assignment_list:
    assignment [, assignment] ...

INSERT inserts new rows into an existing table. The INSERT ... VALUES
and INSERT ... SET forms of the statement insert rows based on
explicitly specified values. The INSERT ... SELECT form inserts rows
selected from another table or tables. INSERT with an ON DUPLICATE KEY
UPDATE clause enables existing rows to be updated if a row to be
inserted would cause a duplicate value in a UNIQUE index or PRIMARY
KEY.

For additional information about INSERT ... SELECT and INSERT ... ON
DUPLICATE KEY UPDATE, see [HELP INSERT SELECT], and
http://dev.mysql.com/doc/refman/5.7/en/insert-on-duplicate.html.

In MySQL 5.7, the DELAYED keyword is accepted but ignored by the
server. For the reasons for this, see [HELP INSERT DELAYED],

Inserting into a table requires the INSERT privilege for the table. If
the ON DUPLICATE KEY UPDATE clause is used and a duplicate key causes
an UPDATE to be performed instead, the statement requires the UPDATE
privilege for the columns to be updated. For columns that are read but
not modified you need only the SELECT privilege (such as for a column
referenced only on the right hand side of an col_name=expr assignment
in an ON DUPLICATE KEY UPDATE clause).

When inserting into a partitioned table, you can control which
partitions and subpartitions accept new rows. The PARTITION option
takes a list of the comma-separated names of one or more partitions or
subpartitions (or both) of the table. If any of the rows to be inserted
by a given INSERT statement do not match one of the partitions listed,
the INSERT statement fails with the error Found a row not matching the
given partition set. For more information and examples, see
http://dev.mysql.com/doc/refman/5.7/en/partitioning-selection.html.

URL: http://dev.mysql.com/doc/refman/5.7/en/insert.html


mysql>

10-存儲引擎介紹

一、什麼是存儲引擎?

  • MySQL中建立的庫==文件夾
  • MySQL庫中建立的表==文件

1)咱們知道,現實生活中咱們用來存儲數據的文件有不一樣的類型,每種文件類型對應各自不一樣的處理機制:好比處理文本用txt類型,處理表格用excel,處理圖片用png等;

2)數據庫中的表也應該有不一樣的類型,表的類型不一樣,會對應mysql不一樣的存取機制,表類型又稱爲存儲引擎;

3)存儲引擎說白了就是如何存儲數據、如何爲存儲的數據創建索引和如何更新、查詢數據等技術的實現方
法。由於在關係數據庫中數據的存儲是以表的形式存儲的,因此存儲引擎也能夠稱爲表類型(即存儲和
操做此表的類型)

4)在Oracle 和SQL Server等數據庫中只有一種存儲引擎,全部數據存儲管理機制都是同樣的。而MySql
數據庫提供了多種存儲引擎。用戶能夠根據不一樣的需求爲數據表選擇不一樣的存儲引擎,用戶也能夠根據
本身的須要編寫本身的存儲引擎

SQL 解析器、SQL 優化器、緩衝池、存儲引擎等組件在每一個數據庫中都存在,但不是每 個數據庫都有這麼多存儲引擎。MySQL 的插件式存儲引擎可讓存儲引擎層的開發人員設 計他們但願的存儲層,例如,有的應用須要知足事務的要求,有的應用則不須要對事務有這 麼強的要求 ;有的但願數據能持久存儲,有的只但願放在內存中,臨時並快速地提供對數據 的查詢。

小結:MySQL的存儲引擎即」表的類型「,表即文件,也就是文件的類型,好比經常使用文件有txt、mp三、jpg;那麼在MySQL中指不一樣的表類型;

二、MySQL支持的存儲引擎;

show engines;
mysql> show engines;
+--------------------+---------+----------------------------------------------------------------+--------------+------+------------+
| Engine             | Support | Comment                                                        | Transactions | XA   | Savepoints |
+--------------------+---------+----------------------------------------------------------------+--------------+------+------------+
| InnoDB             | DEFAULT | Supports transactions, row-level locking, and foreign keys     | YES          | YES  | YES        |
| MRG_MYISAM         | YES     | Collection of identical MyISAM tables                          | NO           | NO   | NO         |
| MEMORY             | YES     | Hash based, stored in memory, useful for temporary tables      | NO           | NO   | NO         |
| BLACKHOLE          | YES     | /dev/null storage engine (anything you write to it disappears) | NO           | NO   | NO         |
| MyISAM             | YES     | MyISAM storage engine                                          | NO           | NO   | NO         |
| CSV                | YES     | CSV storage engine                                             | NO           | NO   | NO         |
| ARCHIVE            | YES     | Archive storage engine                                         | NO           | NO   | NO         |
| PERFORMANCE_SCHEMA | YES     | Performance Schema                                             | NO           | NO   | NO         |
| FEDERATED          | NO      | Federated MySQL storage engine                                 | NULL         | NULL | NULL       |
+--------------------+---------+----------------------------------------------------------------+--------------+------+------------+
9 rows in set (0.00 sec)

mysql>

1)、InnoDB 存儲引擎

支持事務,其設計目標主要面向聯機事務處理(OLTP)的應用。其

特色是行鎖設計、支持外鍵,並支持相似 Oracle 的非鎖定讀,即默認讀取操做不會產生鎖。 從 MySQL 5.5.8 版本開始是默認的存儲引擎。

InnoDB 存儲引擎將數據放在一個邏輯的表空間中,這個表空間就像黑盒同樣由 InnoDB 存儲引擎自身來管理。從 MySQL 4.1(包括 4.1)版本開始,能夠將每一個 InnoDB 存儲引擎的 表單獨存放到一個獨立的 ibd 文件中。此外,InnoDB 存儲引擎支持將裸設備(row disk)用 於創建其表空間。

InnoDB 經過使用多版本併發控制(MVCC)來得到高併發性,而且實現了 SQL 標準 的 4 種隔離級別,默認爲 REPEATABLE 級別,同時使用一種稱爲 netx-key locking 的策略來 避免幻讀(phantom)現象的產生。除此以外,InnoDB 存儲引擎還提供了插入緩衝(insert buffer)、二次寫(double write)、自適應哈希索引(adaptive hash index)、預讀(read ahead) 等高性能和高可用的功能。

對於表中數據的存儲,InnoDB 存儲引擎採用了彙集(clustered)的方式,每張表都是按 主鍵的順序進行存儲的,若是沒有顯式地在表定義時指定主鍵,InnoDB 存儲引擎會爲每一 行生成一個 6 字節的 ROWID,並以此做爲主鍵。

InnoDB 存儲引擎是 MySQL 數據庫最爲經常使用的一種引擎,Facebook、Google、Yahoo 等 公司的成功應用已經證實了 InnoDB 存儲引擎具有高可用性、高性能以及高可擴展性。對其 底層實現的掌握和理解也須要時間和技術的積累。若是想深刻了解 InnoDB 存儲引擎的工做 原理、實現和應用,能夠參考《MySQL 技術內幕:InnoDB 存儲引擎》一書。

2)、MyISAM 存儲引擎

不支持事務、表鎖設計、支持全文索引,主要面向一些 OLAP 數 據庫應用,在 MySQL 5.5.8 版本以前是默認的存儲引擎(除 Windows 版本外)。數據庫系統 與文件系統一個很大的不一樣在於對事務的支持,MyISAM 存儲引擎是不支持事務的。究其根 本,這也並不難理解。用戶在全部的應用中是否都須要事務呢?在數據倉庫中,若是沒有 ETL 這些操做,只是簡單地經過報表查詢還須要事務的支持嗎?此外,MyISAM 存儲引擎的 另外一個不同凡響的地方是,它的緩衝池只緩存(cache)索引文件,而不緩存數據文件,這與 大多數的數據庫都不相同。

3)、NDB 存儲引擎

年,MySQL AB 公司從 Sony Ericsson 公司收購了 NDB 存儲引擎。 NDB 存儲引擎是一個集羣存儲引擎,相似於 Oracle 的 RAC 集羣,不過與 Oracle RAC 的 share everything 結構不一樣的是,其結構是 share nothing 的集羣架構,所以能提供更高級別的 高可用性。NDB 存儲引擎的特色是數據所有放在內存中(從 5.1 版本開始,能夠將非索引數 據放在磁盤上),所以主鍵查找(primary key lookups)的速度極快,而且可以在線添加 NDB 數據存儲節點(data node)以便線性地提升數據庫性能。因而可知,NDB 存儲引擎是高可用、 高性能、高可擴展性的數據庫集羣系統,其面向的也是 OLTP 的數據庫應用類型。

4)、Memory 存儲引擎

正如其名,Memory 存儲引擎中的數據都存放在內存中,數據庫重 啓或發生崩潰,表中的數據都將消失。它很是適合於存儲 OLTP 數據庫應用中臨時數據的臨時表,也能夠做爲 OLAP 數據庫應用中數據倉庫的維度表。Memory 存儲引擎默認使用哈希 索引,而不是一般熟悉的 B+ 樹索引。

5)、Infobright 存儲引擎

第三方的存儲引擎。其特色是存儲是按照列而非行的,所以很是 適合 OLAP 的數據庫應用。其官方網站是 http://www.infobright.org/,上面有很多成功的數據 倉庫案例可供分析。

6)、NTSE 存儲引擎

網易公司開發的面向其內部使用的存儲引擎。目前的版本不支持事務, 但提供壓縮、行級緩存等特性,不久的未來會實現面向內存的事務支持。

7)、BLACKHOLE

黑洞存儲引擎,能夠應用於主備複製中的分發主庫。

MySQL 數據庫還有不少其餘存儲引擎,上述只是列舉了最爲經常使用的一些引擎。若是 你喜歡,徹底能夠編寫專屬於本身的引擎,這就是開源賦予咱們的能力,也是開源的魅 力所在。

三、使用存儲引擎;

方法一:建表時候指定;

create table tb1(id int,name varchar(30))engine = InnoDB charset utf8;
create table tb2(id int,name varchar(30))engine = Memory charset utf8;
create table tb3(id int,name varchar(30))engine = Blackhole charset utf8;
create table tb4(id int,name varchar(30))engine = MyISAM charset utf8;

方法二:在配置文件中指定默認的存儲引擎(編輯/etc/my.cnf)

[root@iZ2ze2m3z176dpbiaolifiZ ~]# cat /etc/my.cnf
# For advice on how to change settings please see
# http://dev.mysql.com/doc/refman/5.7/en/server-configuration-defaults.html

[mysqld]
#
# 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
#
# 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
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock

# Disabling symbolic-links is recommended to prevent assorted security risks
symbolic-links=0

log-error=/var/log/mysqld.log
pid-file=/var/run/mysqld/mysqld.pid
character_set_server=utf8
default-storage-engine=INNODB
innodb_file_per_table=1
[root@iZ2ze2m3z176dpbiaolifiZ ~]# 

操做日誌;

Enter password: ************
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 22
Server version: 5.7.20-log MySQL Community Server (GPL)

Copyright (c) 2000, 2017, 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> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| luffycity          |
| mysql              |
| performance_schema |
| sakila             |
| sys                |
| world              |
+--------------------+
7 rows in set (0.00 sec)

mysql> create database engines charset utf8;
Query OK, 1 row affected (0.00 sec)

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| engines            |
| luffycity          |
| mysql              |
| performance_schema |
| sakila             |
| sys                |
| world              |
+--------------------+
8 rows in set (0.00 sec)

mysql> use engines;
Database changed
mysql> creata table tb1(id int,name varchar(30))engine = InnoDB charset utf8;
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 'creata table tb1(id int,name varchar(30))engine = InnoDB charset utf8' at line 1
mysql> create table tb1(id int,name varchar(30))engine = InnoDB charset utf8;
Query OK, 0 rows affected (0.01 sec)

mysql> create table tb2(id int,name varchar(30))engine = Memory charset utf8;
Query OK, 0 rows affected (0.00 sec)

mysql> create table tb3(id int,name varchar(30))engine = Blackhole charset utf8;
Query OK, 0 rows affected (0.00 sec)

mysql> create table tb4(id int,name varchar(30))engine = MyISAM charset utf8;
Query OK, 0 rows affected (0.00 sec)

mysql> show tables;
+-------------------+
| Tables_in_engines |
+-------------------+
| tb1               |
| tb2               |
| tb3               |
| tb4               |
+-------------------+
4 rows in set (0.00 sec)

mysql> show engines \G;
*************************** 1. row ***************************
      Engine: InnoDB
     Support: DEFAULT
     Comment: Supports transactions, row-level locking, and foreign keys
Transactions: YES
          XA: YES
  Savepoints: YES
*************************** 2. row ***************************
      Engine: MRG_MYISAM
     Support: YES
     Comment: Collection of identical MyISAM tables
Transactions: NO
          XA: NO
  Savepoints: NO
*************************** 3. row ***************************
      Engine: MEMORY
     Support: YES
     Comment: Hash based, stored in memory, useful for temporary tables
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: MyISAM
     Support: YES
     Comment: MyISAM storage engine
Transactions: NO
          XA: NO
  Savepoints: NO
*************************** 6. row ***************************
      Engine: CSV
     Support: YES
     Comment: CSV storage engine
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: PERFORMANCE_SCHEMA
     Support: YES
     Comment: Performance Schema
Transactions: NO
          XA: NO
  Savepoints: NO
*************************** 9. row ***************************
      Engine: FEDERATED
     Support: NO
     Comment: Federated MySQL storage engine
Transactions: NULL
          XA: NULL
  Savepoints: NULL
9 rows in set (0.00 sec)

ERROR:
No query specified

mysql> show engines ;
+--------------------+---------+----------------------------------------------------------------+--------------+------+------------+
| Engine             | Support | Comment                                                        | Transactions | XA   | Savepoints |
+--------------------+---------+----------------------------------------------------------------+--------------+------+------------+
| InnoDB             | DEFAULT | Supports transactions, row-level locking, and foreign keys     | YES          | YES  | YES        |
| MRG_MYISAM         | YES     | Collection of identical MyISAM tables                          | NO           | NO   | NO         |
| MEMORY             | YES     | Hash based, stored in memory, useful for temporary tables      | NO           | NO   | NO         |
| BLACKHOLE          | YES     | /dev/null storage engine (anything you write to it disappears) | NO           | NO   | NO         |
| MyISAM             | YES     | MyISAM storage engine                                          | NO           | NO   | NO         |
| CSV                | YES     | CSV storage engine                                             | NO           | NO   | NO         |
| ARCHIVE            | YES     | Archive storage engine                                         | NO           | NO   | NO         |
| PERFORMANCE_SCHEMA | YES     | Performance Schema                                             | NO           | NO   | NO         |
| FEDERATED          | NO      | Federated MySQL storage engine                                 | NULL         | NULL | NULL       |
+--------------------+---------+----------------------------------------------------------------+--------------+------+------------+
9 rows in set (0.00 sec)

mysql> show variables like 'storage_engine%';
Empty set, 1 warning (0.00 sec)

mysql> show variables like 'storage_engine';
Empty set, 1 warning (0.00 sec)

mysql> show variables like 'storage_engine%';
Empty set, 1 warning (0.00 sec)

mysql> show variables like 'storage_engine';;
Empty set, 1 warning (0.00 sec)

ERROR:
No query specified

mysql> show variables like 'storage_engine';
Empty set, 1 warning (0.00 sec)

mysql>

11-表的增刪改查

1、表介紹;

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

總結:

  • 行稱之爲記錄
  • 列稱之爲字段

2、建立表;

語法:

CREATE TABLE 表名(
字段名1,數據類型 [列級別約束條件] [默認值],
字段名2,數據類型 [列級別約束條件] [默認值],
......
[表級別約束條件]
);

示例:

CREATE DATABASE luffycity CHARSET utf8;

USE luffycity;

CREATE TABLE userinfo(
id int,
name varchar(50),
sex enum('',''),
age int(3)
);

SHOW TABLES;

3、查看錶結構;

DESCRIBE userinfo;
DESC userinfo;
SHOW CREATE TABLE userinfo\G;

4、修改表結構(修改表的結構而不是記錄);

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

2、增長字段
    ALTER TABLE 表名 ADD 字段名 數據類型 [完整性約束條件...],
    ADD 字段名 數據類型 [完整性約束條件...],
    ADD 字段名 數據類型 [完整性約束條件...];
    
    ALTER TABLE 表名 ADD 字段名 數據類型 [完整性約束條件...] FIRST;
    ALTER TABLE 表名 ADD 字段名 數據類型 [完整性約束條件...] AFTER 字段名;

3、刪除字段
    ALTER TABLE 表名 DROP 字段名;

4、修改字段

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

5、複製表;


一、複製表結構和記錄;複製表結構+記錄 (key不會複製: 主鍵、外鍵和索引)
SELECT * FORM userinfo WHERE 1=2;#條件爲假,查不到任何記錄
CREATE TABLE copy_user SELECT host,user FROM mysql.user;#複製表結構和記錄;
CREATE TABLE copy_user SELECT host,user FROM mysql.user WHERE 1=2;#條件爲假,僅複製表結構;

   二、like複製;

CREATE TABLE new_user LIKE mysql.user;

6、刪除表;

DROP TABLE 表名;

操做日誌:

Enter password: ************
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 29
Server version: 5.7.20-log MySQL Community Server (GPL)

Copyright (c) 2000, 2017, 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> SHOW DATABASES;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| engines            |
| mysql              |
| performance_schema |
| sakila             |
| sys                |
| world              |
+--------------------+
7 rows in set (0.00 sec)

mysql> CREATE DATABASE luffycity CHARSET utf8;
Query OK, 1 row affected (0.00 sec)

mysql> SHOW DATABASES;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| engines            |
| luffycity          |
| mysql              |
| performance_schema |
| sakila             |
| sys                |
| world              |
+--------------------+
8 rows in set (0.00 sec)

mysql> USE luffycity;
Database changed
mysql> SHOW TABLES;
Empty set (0.00 sec)

mysql> CREATE TABLE userinfo();
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 ')' at line 1
mysql> CREATE TABLE userinfo(
    -> id int,
    -> name varchar(50),
    -> sex enum('male','female'),
    -> age int(3)
    -> );
Query OK, 0 rows affected (0.02 sec)

mysql> SHOW CREATE TABLE userinfo;
+----------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table    | Create Table                                                                                                                                                                                           |
+----------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| userinfo | CREATE TABLE `userinfo` (
  `id` int(11) DEFAULT NULL,
  `name` varchar(50) DEFAULT NULL,
  `sex` enum('male','female') DEFAULT NULL,
  `age` int(3) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 |
+----------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

mysql> SHOW CREATE TABLE userinfo\G;
*************************** 1. row ***************************
       Table: userinfo
Create Table: CREATE TABLE `userinfo` (
  `id` int(11) DEFAULT NULL,
  `name` varchar(50) DEFAULT NULL,
  `sex` enum('male','female') DEFAULT NULL,
  `age` int(3) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8
1 row in set (0.00 sec)

ERROR:
No query specified

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

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

mysql> SELECT id,name,sex,age FROM userinfo;
Empty set (0.00 sec)

mysql> SELECT * FORM userinfo;
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 'FORM userinfo' at line 1
mysql> SELECT * FROM userinfo;
Empty set (0.00 sec)

mysql> SELECT id,age,sex FROM userinfo;
Empty set (0.00 sec)

mysql> INSERT INTO userinfo VALUES
    -> (1,'cuixiaozhao',26,'male'),
    -> (2,'lijingping',22,'male'),
    -> (3,'gaozhifen',50,'female'),
    -> (4,'cuiqingliang',50,'female');
ERROR 1265 (01000): Data truncated for column 'sex' at row 1
mysql> INSERT INTO userinfo VALUES
    -> (1,'cuixiaozhao',26,'male'),
    -> (2,'lijingping',22,'male');
ERROR 1265 (01000): Data truncated for column 'sex' at row 1
mysql> INSERT INTO userinfo VALUES
    -> (1,'cuixiaozhao','male,26'),
    -> (2,'lijingping','male,22'),
    -> (3,'gaozhifen','female',50),
    -> (4,'cuiqingliang','female',50);
ERROR 1136 (21S01): Column count doesn't match value count at row 1
mysql> SHOW CREATE TABLE userinfo;
+----------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table    | Create Table                                                                                                                                                                                           |
+----------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| userinfo | CREATE TABLE `userinfo` (
  `id` int(11) DEFAULT NULL,
  `name` varchar(50) DEFAULT NULL,
  `sex` enum('male','female') DEFAULT NULL,
  `age` int(3) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 |
+----------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

mysql> INSERT INTO userinfo VALUES
    -> (1,'cuixiaozhao','male',26),
    -> (2,'lijingping','female',22),
    -> (3,'gaozhifen','female',50),
    -> (4,'cuiqingliang',50,'male');
ERROR 1265 (01000): Data truncated for column 'sex' at row 4
mysql> INSERT INTO userinfo VALUES
    -> (1,'cuixiaozhao','male',26),
    -> (2,'lijingping','female',22),
    -> (3,'gaozhifen','female',50),
    -> (4,'cuiqingliang','male',50);
Query OK, 4 rows affected (0.00 sec)
Records: 4  Duplicates: 0  Warnings: 0

mysql> SELECT * FROM userinfo;
+------+--------------+--------+------+
| id   | name         | sex    | age  |
+------+--------------+--------+------+
|    1 | cuixiaozhao  | male   |   26 |
|    2 | lijingping   | female |   22 |
|    3 | gaozhifen    | female |   50 |
|    4 | cuiqingliang | male   |   50 |
+------+--------------+--------+------+
4 rows in set (0.00 sec)

mysql> ALTER TABLE userinfo RENAME familyinfo;
Query OK, 0 rows affected (0.01 sec)

mysql> SHOW TABLES;
+---------------------+
| Tables_in_luffycity |
+---------------------+
| familyinfo          |
+---------------------+
1 row in set (0.00 sec)

mysql> SELECT * FROM familyinfo;
+------+--------------+--------+------+
| id   | name         | sex    | age  |
+------+--------------+--------+------+
|    1 | cuixiaozhao  | male   |   26 |
|    2 | lijingping   | female |   22 |
|    3 | gaozhifen    | female |   50 |
|    4 | cuiqingliang | male   |   50 |
+------+--------------+--------+------+
4 rows in set (0.00 sec)

mysql> ALTER TABLE familyinfo ADD hometown varchar(50),tel int(11);
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 'tel int(11)' at line 1
mysql> ALTER TABLE familyinfo ADD hometown varchar(50),ADD tel int(11);
Query OK, 0 rows affected (0.06 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> SHOW CRATE TABLE familyinfo;
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 'CRATE TABLE familyinfo' at line 1
mysql> SHOW CREATE TABLE familyinfo;
+------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table      | Create Table                                                                                                                                                                                                                                                                  |
+------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| familyinfo | CREATE TABLE `familyinfo` (
  `id` int(11) DEFAULT NULL,
  `name` varchar(50) DEFAULT NULL,
  `sex` enum('male','female') DEFAULT NULL,
  `age` int(3) DEFAULT NULL,
  `hometown` varchar(50) DEFAULT NULL,
  `tel` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 |
+------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

mysql> DESC familyinfo;
+----------+-----------------------+------+-----+---------+-------+
| Field    | Type                  | Null | Key | Default | Extra |
+----------+-----------------------+------+-----+---------+-------+
| id       | int(11)               | YES  |     | NULL    |       |
| name     | varchar(50)           | YES  |     | NULL    |       |
| sex      | enum('male','female') | YES  |     | NULL    |       |
| age      | int(3)                | YES  |     | NULL    |       |
| hometown | varchar(50)           | YES  |     | NULL    |       |
| tel      | int(11)               | YES  |     | NULL    |       |
+----------+-----------------------+------+-----+---------+-------+
6 rows in set (0.00 sec)

mysql> SELECT * FORM familyinfo;
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 'FORM familyinfo' at line 1
mysql> SELECT * FROM familyinfo;
+------+--------------+--------+------+----------+------+
| id   | name         | sex    | age  | hometown | tel  |
+------+--------------+--------+------+----------+------+
|    1 | cuixiaozhao  | male   |   26 | NULL     | NULL |
|    2 | lijingping   | female |   22 | NULL     | NULL |
|    3 | gaozhifen    | female |   50 | NULL     | NULL |
|    4 | cuiqingliang | male   |   50 | NULL     | NULL |
+------+--------------+--------+------+----------+------+
4 rows in set (0.00 sec)

mysql> ALTER TABLE familyinfo ADD birth int(20) FIRST;
Query OK, 0 rows affected (0.05 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> SELECT * FORM familyinfo\G;
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 'FORM familyinfo' at line 1
ERROR:
No query specified

mysql> SELECT * FROM familyinfo\G;
*************************** 1. row ***************************
   birth: NULL
      id: 1
    name: cuixiaozhao
     sex: male
     age: 26
hometown: NULL
     tel: NULL
*************************** 2. row ***************************
   birth: NULL
      id: 2
    name: lijingping
     sex: female
     age: 22
hometown: NULL
     tel: NULL
*************************** 3. row ***************************
   birth: NULL
      id: 3
    name: gaozhifen
     sex: female
     age: 50
hometown: NULL
     tel: NULL
*************************** 4. row ***************************
   birth: NULL
      id: 4
    name: cuiqingliang
     sex: male
     age: 50
hometown: NULL
     tel: NULL
4 rows in set (0.00 sec)

ERROR:
No query specified

mysql> ALTER TABLE familyinfo ADD job varchar(40) AFTER hometown;
Query OK, 0 rows affected (0.05 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> ALTER TABLE familyinfo MODIFY job char(20);
Query OK, 4 rows affected (0.04 sec)
Records: 4  Duplicates: 0  Warnings: 0

mysql> ALTER TABLE familyinfo CHANGE tel telnum int(11);
Query OK, 0 rows affected (0.01 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> ALTER TABLE familyinfo CHANGE telnum telphone int(14);
Query OK, 0 rows affected (0.01 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> SHOW CREATE TABLE familyinfo;
+------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table      | Create Table                                                                                                                                                                                                                                                                                                                                      |
+------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| familyinfo | CREATE TABLE `familyinfo` (
  `birth` int(20) DEFAULT NULL,
  `id` int(11) DEFAULT NULL,
  `name` varchar(50) DEFAULT NULL,
  `sex` enum('male','female') DEFAULT NULL,
  `age` int(3) DEFAULT NULL,
  `hometown` varchar(50) DEFAULT NULL,
  `job` char(20) DEFAULT NULL,
  `telphone` int(14) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 |
+------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

mysql> SHOW CREATE TABLE familyinfo\G;
*************************** 1. row ***************************
       Table: familyinfo
Create Table: CREATE TABLE `familyinfo` (
  `birth` int(20) DEFAULT NULL,
  `id` int(11) DEFAULT NULL,
  `name` varchar(50) DEFAULT NULL,
  `sex` enum('male','female') DEFAULT NULL,
  `age` int(3) DEFAULT NULL,
  `hometown` varchar(50) DEFAULT NULL,
  `job` char(20) DEFAULT NULL,
  `telphone` int(14) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8
1 row in set (0.00 sec)

ERROR:
No query specified

mysql> ALTER TABLE familyinfo ENGINE = MyISAM;
Query OK, 4 rows affected (0.02 sec)
Records: 4  Duplicates: 0  Warnings: 0

mysql> SHOW CREATE TABLE familyinfo\G;
*************************** 1. row ***************************
       Table: familyinfo
Create Table: CREATE TABLE `familyinfo` (
  `birth` int(20) DEFAULT NULL,
  `id` int(11) DEFAULT NULL,
  `name` varchar(50) DEFAULT NULL,
  `sex` enum('male','female') DEFAULT NULL,
  `age` int(3) DEFAULT NULL,
  `hometown` varchar(50) DEFAULT NULL,
  `job` char(20) DEFAULT NULL,
  `telphone` int(14) DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8
1 row in set (0.00 sec)

ERROR:
No query specified

mysql> ALTER TABLE familyinfo ENGINE = InnoDB;
Query OK, 4 rows affected (0.03 sec)
Records: 4  Duplicates: 0  Warnings: 0

mysql> ALTER TABLE familyinfo MODIFY id int(11) not null PRIMARY KEY;
Query OK, 0 rows affected (0.05 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> SHOW CREATE TABLE familyinfo\G;
*************************** 1. row ***************************
       Table: familyinfo
Create Table: CREATE TABLE `familyinfo` (
  `birth` int(20) DEFAULT NULL,
  `id` int(11) NOT NULL,
  `name` varchar(50) DEFAULT NULL,
  `sex` enum('male','female') DEFAULT NULL,
  `age` int(3) DEFAULT NULL,
  `hometown` varchar(50) DEFAULT NULL,
  `job` char(20) DEFAULT NULL,
  `telphone` int(14) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
1 row in set (0.00 sec)

ERROR:
No query specified

mysql> ALTER TABLE familyinfo MODIFY id int(11) not null PRIMARY KEY AUTO INCREMENT;
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 'AUTO INCREMENT' at line 1
mysql> ALTER TABLE familyinfo MODIFY id int(11) not null PRIMARY KEY AUTO_INCREMENT;
ERROR 1068 (42000): Multiple primary key defined
mysql> ALTER TABLE familyinfo MODIFY id int(11) not null  AUTO_INCREMENT;
Query OK, 4 rows affected (0.03 sec)
Records: 4  Duplicates: 0  Warnings: 0

mysql> SHOW CREATE TABLE familyinfo;
+------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table      | Create Table                                                                                                                                                                                                                                                                                                                                                                                        |
+------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| familyinfo | CREATE TABLE `familyinfo` (
  `birth` int(20) DEFAULT NULL,
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) DEFAULT NULL,
  `sex` enum('male','female') DEFAULT NULL,
  `age` int(3) DEFAULT NULL,
  `hometown` varchar(50) DEFAULT NULL,
  `job` char(20) DEFAULT NULL,
  `telphone` int(14) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8 |
+------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

mysql> ALTER TABLE familyinfo 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 familyinfo DROP telphone;
Query OK, 0 rows affected (0.05 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> SHOW CTEATE TABLE familyinfo;
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 'CTEATE TABLE familyinfo' at line 1
mysql> SHOW CREATE TABLE familyinfo;
+------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table      | Create Table                                                                                                                                                                                                                                                                                                                                                     |
+------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| familyinfo | CREATE TABLE `familyinfo` (
  `birth` int(20) DEFAULT NULL,
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) DEFAULT NULL,
  `sex` enum('male','female') DEFAULT NULL,
  `age` int(3) DEFAULT NULL,
  `hometown` varchar(50) DEFAULT NULL,
  `job` char(20) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8 |
+------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

mysql>

12-整數類型;

一、數值類型;

1)整數類型

  • TINYINT    很小的整數~1個字節;
    tinyint[(m)] [unsigned] [zerofill]
  • SMALLINT    小的整數~2個字節;  
    int[(m)][unsigned][zerofill]
  • MEDIUMINT    中等大小的整數~3個字節;
  • INT    普通大小的整數~4個字節;
    int[(m)][unsigned][zerofill]
  • BIGINT    大整數~8個字節;
    bigint[(m)][unsigned][zerofill]

用途:做用:存儲年齡,等級,id,各類號碼等;

2)浮點小數數據類型

  • FLOAT 
定義:單精度浮點數(非準確小數值),m是數字總個數,d是小數點後個數。m最大值爲255,d最大值爲30
精確度:**** 隨着小數的增多,精度變得不許確 ****
用法:FLOAT[(M,D)] [UNSIGNED] [ZEROFILL]
  • DOUBLE

定義:雙精度浮點數(非準確小數值),m是數字總個數,d是小數點後個數。m最大值爲255,d最大值爲30

精確度:****隨着小數的增多,精度比float要高,但也會變得不許確 ****

用法:DOUBLE[(M,D)] [UNSIGNED] [ZEROFILL]

做用:存儲薪資、身高、體重、體質參數等

3)定點小數類型

  • DECIMAL 

定義:準確的小數值,m是數字總個數(負號不算),d是小數點後個數。 m最大值爲65,d最大值爲30。

精確度:**** 隨着小數的增多,精度始終準確 ****,對於精確數值計算時須要用此類型

decaimal可以存儲精確值的緣由在於其內部按照字符串存儲。

  • 注意:爲該類型指定寬度時,僅僅只是指定查詢結果的顯示寬度,與存儲範圍無關,存儲範圍以下:

  • 其實咱們徹底不必爲整數類型指定顯示寬度,使用默認的就能夠了;

  • 默認的顯示寬度,都是在最大值的基礎上加1

  • 有符號和無符號的最大數字須要的顯示寬度均爲10,而針對有符號的最小值則須要11位才能顯示徹底,因此int類型默認的顯示寬度爲11是很是合理的(由於加上1位符號)

13-日期類型

一、MySQL中表示日期的數據類型主要有;

  • YEAR ~YYYY(1901/2155)
  • TIME~YYYY--MM--DD(1000-01-01/9999-12-31)
  • DATE~HH:MM:SS('-838:59:59/838:59:59')
  • DATETIME~YYYY-MM-DD HH:MM:SS (1000-01-01 00:00:00/9999-12-31 23:59:59)
  • TIMESTAMP~YYYYMMDD HHMMSS(1970-01-01 00:00:00/2037 年某時)

二、注意啦;

============注意啦,注意啦,注意啦===========
1. 單獨插入時間時,須要以字符串的形式,按照對應的格式插入;如'2018'
2. 插入年份時,儘可能使用4位值;
3. 插入兩位年份時,<=69,以20開頭,好比50,  結果2050      
                >=70,以19開頭,好比71,結果1971

三、datetime和timestamp的區別;

1.DATETIME的日期範圍是1001——9999年,TIMESTAMP的時間範圍是1970——2038年。
2.DATETIME存儲時間與時區無關,TIMESTAMP存儲時間與時區有關,顯示的值也依賴於時區。在mysql服務器,
操做系統以及客戶端鏈接都有時區的設置。

3.DATETIME使用8字節的存儲空間,TIMESTAMP的存儲空間爲4字節。所以,TIMESTAMP比DATETIME的空間利用率更高。

4.DATETIME的默認值爲null;TIMESTAMP的字段默認不爲空(not null),默認值爲當前時間(CURRENT_TIMESTAMP),
若是不作特殊處理,而且update語句中沒有指定該列的更新值,則默認更新爲當前時間。

14-字符類型

一、char(定長)與varchar(變長);

#char類型:定長,簡單粗暴,浪費空間,存取速度快
    字符長度範圍:0-255(一箇中文是一個字符,是utf8編碼的3個字節)
    存儲:
        存儲char類型的值時,會往右填充空格來知足長度
        例如:指定長度爲10,存>10個字符則報錯,存<10個字符則用空格填充直到湊夠10個字符存儲

    檢索:
        在檢索或者說查詢時,查出的結果會自動刪除尾部的空格,除非咱們打開pad_char_to_full_length SQL模式(SET sql_mode = 'PAD_CHAR_TO_FULL_LENGTH';)

#varchar類型:變長,精準,節省空間,存取速度慢
    字符長度範圍:0-65535(若是大於21845會提示用其餘類型 。mysql行最大限制爲65535字節,字符編碼爲utf-8:https://dev.mysql.com/doc/refman/5.7/en/column-count-limit.html)
    存儲:
        varchar類型存儲數據的真實內容,不會用空格填充,若是'ab  ',尾部的空格也會被存起來
        強調:varchar類型會在真實數據前加1-2Bytes的前綴,該前綴用來表示真實數據的bytes字節數(1-2Bytes最大表示65535個數字,正好符合mysql對row的最大字節限制,即已經足夠使用)
        若是真實的數據<255bytes則須要1Bytes的前綴(1Bytes=8bit 2**8最大表示的數字爲255)
        若是真實的數據>255bytes則須要2Bytes的前綴(2Bytes=16bit 2**16最大表示的數字爲65535)

    檢索:
        尾部有空格會保存下來,在檢索或者說查詢時,也會正常顯示包含空格在內的內容

  • 1. char填充空格來知足固定長度,可是在查詢時卻會很不要臉地刪除尾部的空格(裝做本身好像沒有浪費過空間同樣),而後修改sql_mode讓其現出原形;
  • 2. 雖然 CHAR 和 VARCHAR 的存儲方式不太相同,可是對於兩個字符串的比較,都只比 較其值,忽略 CHAR 值存在的右填充,即便將 SQL _MODE 設置爲 PAD_CHAR_TO_FULL_ LENGTH 也同樣,,但這不適用於like;

小結:

一、大多數狀況下,通常用char;

二、同一張表,不該該char與varchar共存,要麼都是前者,要麼都是後者;

三、在一張表中,char的數據類型應該靠前存放;

四、char和varchar括號內的參數指的是字符的長度;

#經常使用字符串系列:char與varchar
注:雖然varchar使用起來較爲靈活,可是從整個系統的性能角度來講,char數據類型的處理速度更快,有時甚至能夠超出varchar處理速度的50%。所以,用戶在設計數據庫時應當綜合考慮各方面的因素,以求達到最佳的平衡

#其餘字符串系列(效率:char>varchar>text)
TEXT系列 TINYTEXT TEXT MEDIUMTEXT LONGTEXT
BLOB 系列    TINYBLOB BLOB MEDIUMBLOB LONGBLOB 
BINARY系列 BINARY VARBINARY

text:text數據類型用於保存變長的大字符串,能夠組多到65535 (2**161)個字符。
mediumtext:A TEXT column with a maximum length of 16,777,215 (2**241) characters.
longtext:A TEXT column with a maximum length of 4,294,967,295 or 4GB (2**321) characters.

15-枚舉類型與集合類型

一、枚舉類型與集合類型;

說明:字段的值,只能給給定範圍中進行選擇,如單選框,多選框;

  • enum 單選,只能在給定的範圍內選擇一個值,如性別sex:男male,女female;
  • set 多選,在給定的範圍內,能夠選擇一個或一個以上的值,如(愛好1,愛好2,愛好3);

操做日誌:

mysql> create table consumer();
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 ')' at line 1
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.01 sec)

mysql> show create table consumer;
+----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table    | Create Table                                                                                                                                                                                                                                                                                 |
+----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| consumer | CREATE TABLE `consumer` (
  `id` int(11) DEFAULT NULL,
  `name` char(16) DEFAULT NULL,
  `sex` enum('male','female','other') DEFAULT NULL,
  `level` enum('vip1','vip2','vip3') DEFAULT NULL,
  `hobbies` set('play','music','read','run') DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 |
+----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

mysql> insert into consumer values (1,'egon','male','vip2','music,read');
Query OK, 1 row affected (0.00 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','xxxx','vip2','music,read');
ERROR 1265 (01000): Data truncated for column 'sex' at row 1
mysql>

16-約束條件not null與default

一、not null與default;

約束條件與數據類型的寬度同樣,都是可選參數

做用:用於保證數據的完整性和一致性
主要分爲:

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...)
 

 

是否可空,null表示空,非字符串;
not null - 不可空
null - 可空

默認值,建立列時能夠指定默認值,當插入數據時若是未主動設置,則自動添加默認值;

mysql> create table tb16(
    -> id int,
    -> name char(6),
    -> sex enum('male','female')not null default 'male'
    -> );
Query OK, 0 rows affected (0.01 sec)

mysql> insert into t16(id,name) values(1,'egon');
ERROR 1146 (42S02): Table 'luffycity.t16' doesn't exist
mysql> insert into tb16(id,name) values(1,'egon');
Query OK, 1 row affected (0.00 sec)

mysql> select * from tb16;
+------+------+------+
| id   | name | sex  |
+------+------+------+
|    1 | egon | male |
+------+------+------+
1 row in set (0.00 sec)

mysql> insert into tb16(id,name) values (2,'alex');
Query OK, 1 row affected (0.00 sec)

mysql> select * from tb16;
+------+------+------+
| id   | name | sex  |
+------+------+------+
|    1 | egon | male |
|    2 | alex | male |
+------+------+------+
2 rows in set (0.00 sec)

mysql>

17-約束條件unique key

一、惟一約束unique;

  • 方法一
create table department1(
id int,
name varchar(20) unique,
comment varchar(100)
);
  • 方法二
create table department2(
id int,
name varchar(20),
comment varchar(100),
constraint uk_name unique(name)
);
  • 特殊-聯合惟一
mysql> create table services(
    -> id int,
    -> ip char(15),
    -> port int,
    -> unique(id),
    -> unique(ip,port)
    -> );
Query OK, 0 rows affected (0.02 sec)

mysql> insert into services values
    -> (1,'192.168.11.10',80),
    -> (2,'192.168.11.11',81),
    -> (3,'192.168.11.13',80);
Query OK, 3 rows affected (0.00 sec)
Records: 3  Duplicates: 0  Warnings: 0

mysql> select 8 from services;
+---+
| 8 |
+---+
| 8 |
| 8 |
| 8 |
+---+
3 rows in set (0.00 sec)

mysql> select * from services;
+------+---------------+------+
| id   | ip            | port |
+------+---------------+------+
|    1 | 192.168.11.10 |   80 |
|    2 | 192.168.11.11 |   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'
mysql>

18-約束條件primary key

一、主鍵primary key(primary key字段的值不爲空且惟一);

  • 單列主鍵
mysql> create table tb17(
    -> id int primary key,
    -> name char(16)
    -> );
Query OK, 0 rows affected (0.01 sec)

mysql> insert into tb17 vlaues
    -> (1,'egon'),
    -> (2,'alex');
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 'vlaues
(1,'egon'),
(2,'alex')' at line 1
mysql> insert into tb17 vlaues
    -> insert into tb17 values
    -> (1,'egon'),
    -> (2,'alex');
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 'vlaues
insert into tb17 values
(1,'egon'),
(2,'alex')' at line 1
mysql> insert into tb17 values
    -> (1,'egon'),
    -> (2,'alex');
Query OK, 2 rows affected (0.00 sec)
Records: 2  Duplicates: 0  Warnings: 0

mysql> select * from tb17;
+----+------+
| id | name |
+----+------+
|  1 | egon |
|  2 | alex |
+----+------+
2 rows in set (0.00 sec)

mysql> insert into tb17 values (2,'cuixiaozhao');
ERROR 1062 (23000): Duplicate entry '2' for key 'PRIMARY'
mysql> insert into tb17 values (1,'cuixiaozhao');
ERROR 1062 (23000): Duplicate entry '1' for key 'PRIMARY'
mysql> insert into tb17 values (3,'cuixiaozhao');
Query OK, 1 row affected (0.00 sec)

mysql> select * from tb17;
+----+-------------+
| id | name        |
+----+-------------+
|  1 | egon        |
|  2 | alex        |
|  3 | cuixiaozhao |
+----+-------------+
3 rows in set (0.00 sec)

mysql>
  • 多列聯合主鍵(複合主鍵)
mysql> create table tb19(
    -> ip char(16),
    -> port int,
    -> primary key(ip,port)
    -> );
Query OK, 0 rows affected (0.01 sec)

mysql> insert into tb19 values('192.168.10.11',80);
Query OK, 1 row affected (0.00 sec)

mysql> insert into tb19 values('192.168.10.11',81);
Query OK, 1 row affected (0.00 sec)

mysql> insert into tb19 values('192.168.10.12',81);
Query OK, 1 row affected (0.00 sec)

mysql> insert into tb19 values('192.168.10.13',81);
Query OK, 1 row affected (0.00 sec)

mysql> insert into tb19 values('192.168.10.12',81);
ERROR 1062 (23000): Duplicate entry '192.168.10.12-81' for key 'PRIMARY'
mysql> select * from tb19;
+---------------+------+
| ip            | port |
+---------------+------+
| 192.168.10.11 |   80 |
| 192.168.10.11 |   81 |
| 192.168.10.12 |   81 |
| 192.168.10.13 |   81 |
+---------------+------+
4 rows in set (0.00 sec)

mysql>

注意:

一、對於InnoDB存儲引擎來講,一張表內必須有一個字段是主鍵(若是沒有,就自動建立隱藏字段);

二、但一個表內只能有一個主鍵primary key;

三、能夠在字段後面指定primary key,亦可在最後指定primary key;

19-約束條件auto_increment

一、auto_increment自增加約束;

1)不指定id進行插入數據;

mysql> create table tb20(
    -> id int primary key auto_increment,
    -> name char(16)
    -> );
Query OK, 0 rows affected (0.01 sec)

mysql> desc tb20;
+-------+----------+------+-----+---------+----------------+
| 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> insert into tb20 values('cuixiaozhao');
ERROR 1136 (21S01): Column count doesn't match value count at row 1
mysql> insert into tb20(name) values('cuixiaozhao');
Query OK, 1 row affected (0.00 sec)

mysql> insert into tb20(name) values('lijingping');
Query OK, 1 row affected (0.00 sec)

mysql> insert into tb20(name) values('gaozhifen');
Query OK, 1 row affected (0.00 sec)

mysql> insert into tb20(name) values('cuiqingliang');
Query OK, 1 row affected (0.00 sec)

mysql> select * from tb20;
+----+--------------+
| id | name         |
+----+--------------+
|  1 | cuixiaozhao  |
|  2 | lijingping   |
|  3 | gaozhifen    |
|  4 | cuiqingliang |
+----+--------------+
4 rows in set (0.00 sec)

mysql>

2)指定id位置進行插入數據;

mysql> insert into tb20(id,name) values(11,'cuixiaoshan');
Query OK, 1 row affected (0.00 sec)

mysql> insert into tb20(name) values('cuixiaosi);
    '> insert into tb20(name) values('cuixiaosi);
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 'cuixiaosi)' at line 1
mysql> insert into tb20(name) values('cuixiaosi');
Query OK, 1 row affected (0.00 sec)

mysql> select * from tb20;
+----+--------------+
| id | name         |
+----+--------------+
|  1 | cuixiaozhao  |
|  2 | lijingping   |
|  3 | gaozhifen    |
|  4 | cuiqingliang |
| 11 | cuixiaoshan  |
| 12 | cuixiaosi    |
+----+--------------+
6 rows in set (0.00 sec)

mysql>

show variables like 'auto_inc%';

mysql> show variables like 'auto_inc%';
+--------------------------+-------+
| Variable_name            | Value |
+--------------------------+-------+
| auto_increment_increment | 1     |
| auto_increment_offset    | 1     |
+--------------------------+-------+
2 rows in set, 1 warning (0.00 sec)

3)步長概念auto_increment_increment;

4)起始位置的偏移量的概念auto_increment_offset;

5)設置步長;

set session auto_increment_increment = 5;臨時生效

set global auto_increment_increment = 5;永久生效

6)設置起始偏移量;

set gloabl auto increment_offset = 3;

set session auto_increment_offset = 3;

mysql> show variables like 'auto_inc%';
+--------------------------+-------+
| Variable_name            | Value |
+--------------------------+-------+
| auto_increment_increment | 1     |
| auto_increment_offset    | 1     |
+--------------------------+-------+
2 rows in set, 1 warning (0.00 sec)

mysql> set session auto_increment_increment = 5;
Query OK, 0 rows affected (0.00 sec)

mysql> set session auto_increment_offset = 6;
Query OK, 0 rows affected (0.00 sec)

mysql> set session auto_increment_offset = 3;
Query OK, 0 rows affected (0.00 sec)

mysql> show variables like 'auto_inc%';
+--------------------------+-------+
| Variable_name            | Value |
+--------------------------+-------+
| auto_increment_increment | 5     |
| auto_increment_offset    | 3     |
+--------------------------+-------+
2 rows in set, 1 warning (0.00 sec)

mysql> create table tb21(
    -> id int primary key auto_increment,
    -> name char(20)
    -> );
Query OK, 0 rows affected (0.02 sec)

mysql> insert into tb20(name) values('cxz');
Query OK, 1 row affected (0.00 sec)

mysql> insert into tb20(name) values('cxs');
Query OK, 1 row affected (0.00 sec)

mysql> insert into tb20(name) values('ljp');
Query OK, 1 row affected (0.00 sec)

mysql> insert into tb20(id,name) values(20,'ljp');
Query OK, 1 row affected (0.00 sec)

mysql> insert into tb20(id,name) values(21,'cxz');
Query OK, 1 row affected (0.00 sec)

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

mysql> select * from tb20;
+----+--------------+
| id | name         |
+----+--------------+
|  1 | cuixiaozhao  |
|  2 | lijingping   |
|  3 | gaozhifen    |
|  4 | cuiqingliang |
| 11 | cuixiaoshan  |
| 12 | cuixiaosi    |
| 13 | cxz          |
| 18 | cxs          |
| 20 | ljp          |
| 21 | cxz          |
| 23 | ljp          |
+----+--------------+
11 rows in set (0.00 sec)

mysql> insert into tb21(name) values('cxz');
Query OK, 1 row affected (0.00 sec)

mysql> insert into tb21(name) values('cxs');
Query OK, 1 row affected (0.00 sec)

mysql> insert into tb21(id,name) values(30,'cxs');
Query OK, 1 row affected (0.00 sec)

mysql> insert into tb21(id,name) values(31,'cxz');
Query OK, 1 row affected (0.00 sec)

mysql> insert into tb21(id,name) values(32,'ljp');
Query OK, 1 row affected (0.00 sec)

mysql> insert into tb21(name) values('gzf');
Query OK, 1 row affected (0.00 sec)

mysql> insert into tb21(name) values('cql');
Query OK, 1 row affected (0.00 sec)

mysql> select * from tb21;
+----+------+
| id | name |
+----+------+
|  3 | cxz  |
|  8 | cxs  |
| 30 | cxs  |
| 31 | cxz  |
| 32 | ljp  |
| 33 | gzf  |
| 38 | cql  |
+----+------+
7 rows in set (0.00 sec)

mysql>

二、清空表之delete與truncate;

1)注意不要使用delete來清空表,delete的用途是結合where等條件語句進行使用的;

2)清空表的數據理應使用truncate來操做,這樣再次插入數據,索引值從最初的auto_increment_offset開始從新計數;

mysql> truncate tb21;
Query OK, 0 rows affected (0.01 sec)

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

mysql> insert into tb21(name) values('cxz');
Query OK, 1 row affected (0.00 sec)

mysql> insert into tb21(name) values('cql');
Query OK, 1 row affected (0.00 sec)

mysql> select * from tb21;
+----+------+
| id | name |
+----+------+
|  3 | cxz  |
|  8 | cql  |
+----+------+
2 rows in set (0.00 sec)

mysql> show variables like 'auto_incre%';
+--------------------------+-------+
| Variable_name            | Value |
+--------------------------+-------+
| auto_increment_increment | 5     |
| auto_increment_offset    | 3     |
+--------------------------+-------+
2 rows in set, 1 warning (0.00 sec)

mysql>

注意:

起始偏移量要小於等於步長的值,要否則步子太大,扯着淡了。

先設置起始偏移量,再設置步長;

20-約束條件之foreign key

一、什麼是外鍵約束foreign key?

 

foreign key:創建表之間的關係;
#一、創建表關係;
    先創建被關聯的表,而且保證被關聯的表的字段惟一(unique、primary key)
    create table dep(
        id int primary key,
        name char(50),
        comment char(50)
    );
        再創建關聯的表;
create table emp(
    id int primary key,
    name char(50),
    sex enum('male','female'),
    dep_id int,
    foreign key(dep_id) references dep(id) on delete cascade on update cascade
);
#先往被關聯表插入數據;
insert into dep values(1,'IT','技術能力有限部門'),(2,'銷售','銷售能力有限部門'),(3,'財務','花錢特別多的部門');
insert into emp values
(1,'cuixiaozhao','male',1),
(2,'lijingping','female',3),
(3,'cuiqingliang','male',2),
(4,'gaozhifen','female',2);

注意:

一、foreign key 要慎用,後續擴展很是麻煩;

二、經過應用程序的邏輯層面來實現;

三、涉及到數據庫的變更,代碼多數要重構;

四、表之間的3種關係——多對1、多多對、一對一;

21-表關係之多對一

一、表關係之多對一;

  • 出版社(一)
  • 書(多-press_id int,foreign key(press_id) refrence )
#一對多或稱爲多對一
三張表:出版社,做者信息,書

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

關聯方式:foreign key

 

Enter password: ************
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 36
Server version: 5.7.20-log MySQL Community Server (GPL)

Copyright (c) 2000, 2017, 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> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| engines            |
| luffycity          |
| mysql              |
| performance_schema |
| sakila             |
| sys                |
| world              |
+--------------------+
8 rows in set (0.00 sec)

mysql> use luffycity;
Database changed
mysql> show tables;
+---------------------+
| Tables_in_luffycity |
+---------------------+
| consumer            |
| dep                 |
| emp                 |
| familyinfo          |
| info                |
| services            |
| student             |
| tb16                |
| tb17                |
| tb19                |
| tb20                |
| tb21                |
| user                |
+---------------------+
13 rows in set (0.00 sec)

mysql> create table press(
    -> id int primary key auto_increment ,
    -> name varchar(20)
    -> );
Query OK, 0 rows affected (0.01 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.02 sec)

mysql> insert into press(name) values('北京工業地雷出版社'),('人民音樂很差聽出版社'),('知識產權沒有用出版社');
Query OK, 3 rows affected (0.01 sec)
Records: 3  Duplicates: 0  Warnings: 0

mysql> insert into book(name,press_id) values
    -> ('九陽神功',1),
    -> ('九陰真經',2),
    -> ('九陰白骨爪',3),
    -> ('獨孤九劍',3),
    -> ('降龍十巴掌',2),
    -> ('葵花寶典',3);
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 ''九陰白骨爪',3),
('獨孤九劍',3),
('降龍十巴掌',2),
('' at line 3
mysql> insert into book(name,press_id) values
    -> ('九陽神功',1),
    -> ('九陰真經',2),
    -> ('九陰白骨爪',3),
    -> ('獨孤九劍',3),
    -> ('降龍十巴掌',2),
    -> ('葵花寶典',3);
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 '
('九陰白骨爪',3),
('獨孤九劍',3),
('降龍十巴掌',2),
('葵花' at line 3
mysql> insert into book(name,press_id) values
    -> ('九陽神功',1),
    -> ('九陰真經',2),
    -> ('九陰白骨爪',3),
    -> ('獨孤九劍',3),
    -> ('降龍十巴掌',2),
    -> ('葵花寶典',3);
Query OK, 6 rows affected (0.00 sec)
Records: 6  Duplicates: 0  Warnings: 0

mysql> select * from press;
+----+--------------------------------+
| id | name                           |
+----+--------------------------------+
|  1 | 北京工業地雷出版社             |
|  2 | 人民音樂很差聽出版社           |
|  3 | 知識產權沒有用出版社           |
+----+--------------------------------+
3 rows in set (0.00 sec)

mysql> select * from book;
+----+-----------------+----------+
| id | name            | press_id |
+----+-----------------+----------+
|  1 | 九陽神功        |        1 |
|  2 | 九陰真經        |        2 |
|  3 | 九陰白骨爪      |        3 |
|  4 | 獨孤九劍        |        3 |
|  5 | 降龍十巴掌      |        2 |
|  6 | 葵花寶典        |        3 |
+----+-----------------+----------+
6 rows in set (0.00 sec)

mysql>

22-表關係之多對多

一、多對多(即雙向的多對一);

mysql> desc book;
+----------+-------------+------+-----+---------+----------------+
| Field    | Type        | Null | Key | Default | Extra          |
+----------+-------------+------+-----+---------+----------------+
| id       | int(11)     | NO   | PRI | NULL    | auto_increment |
| name     | varchar(20) | YES  |     | NULL    |                |
| press_id | int(11)     | NO   | MUL | NULL    |                |
+----------+-------------+------+-----+---------+----------------+
3 rows in set (0.00 sec)

mysql> desc author;
+-------+-------------+------+-----+---------+----------------+
| Field | Type        | Null | Key | Default | Extra          |
+-------+-------------+------+-----+---------+----------------+
| id    | int(11)     | NO   | PRI | NULL    | auto_increment |
| name  | varchar(20) | YES  |     | NULL    |                |
+-------+-------------+------+-----+---------+----------------+
2 rows in set (0.00 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 (0.01 sec)

mysql>
mysql>
mysql> insert into author(name) values('egon'),('alex'),('yuanhao'),('wpq');
Query OK, 4 rows affected (0.00 sec)
Records: 4  Duplicates: 0  Warnings: 0

mysql> insert into author2book(author_id,book_id) values
    -> (1,2),
    -> (1,2),
    -> (1,3),
    -> (1,4),
    -> (1,5),
    -> (2,1),
    -> (2,6),
    -> (3,4),
    -> (3,5),
    -> (3,6),
    -> (4,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 ')' at line 13
mysql> insert into author2book(author_id,book_id) values
    -> (
    -> (1,2),
    -> (1,2),
    -> (1,3),
    -> (1,4),
    -> (1,5),
    -> (2,1),
    -> (2,6),
    -> (3,4),
    -> (3,5),
    -> (3,6),
    -> (4,1)
    -> );
ERROR 1136 (21S01): Column count doesn't match value count at row 1
mysql> show tables;
+---------------------+
| Tables_in_luffycity |
+---------------------+
| author              |
| author2book         |
| book                |
| consumer            |
| dep                 |
| emp                 |
| familyinfo          |
| info                |
| press               |
| services            |
| student             |
| tb16                |
| tb17                |
| tb19                |
| tb20                |
| tb21                |
| user                |
+---------------------+
17 rows in set (0.00 sec)

mysql> desc author2book
    -> ;
+-----------+---------+------+-----+---------+----------------+
| Field     | Type    | Null | Key | Default | Extra          |
+-----------+---------+------+-----+---------+----------------+
| id        | int(11) | NO   | UNI | NULL    | auto_increment |
| author_id | int(11) | NO   | PRI | NULL    |                |
| book_id   | int(11) | NO   | PRI | NULL    |                |
+-----------+---------+------+-----+---------+----------------+
3 rows in set (0.00 sec)

mysql> insert into author2book(author_id,book_id) values
    -> (
    -> (1,2),
    -> (1,2),
    -> (1,3),
    -> (1,4),
    -> (1,5),
    -> (2,1),
    -> (2,6),
    -> (3,4),
    -> (3,5),
    -> (3,6),
    -> (4,1)
    -> );
ERROR 1136 (21S01): Column count doesn't match value count at row 1
mysql> desc book;
+----------+-------------+------+-----+---------+----------------+
| Field    | Type        | Null | Key | Default | Extra          |
+----------+-------------+------+-----+---------+----------------+
| id       | int(11)     | NO   | PRI | NULL    | auto_increment |
| name     | varchar(20) | YES  |     | NULL    |                |
| press_id | int(11)     | NO   | MUL | NULL    |                |
+----------+-------------+------+-----+---------+----------------+
3 rows in set (0.00 sec)

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

mysql> insert into author2book(author_id,book_id) values
    ->
    -> (1,2),
    -> (1,2),
    -> (1,3),
    -> (1,4),
    -> (1,5),
    -> (2,1),
    -> (2,6),
    -> (3,4),
    -> (3,5),
    -> (3,6),
    -> (4,1);
ERROR 1062 (23000): Duplicate entry '1-2' for key 'PRIMARY'
mysql> insert into author2book(author_id,book_id) values
    -> (1,2),
    -> (1,2),
    -> (1,3),
    -> (1,4),
    -> (1,5),
    -> (2,1),
    -> (2,6),
    -> (3,4),
    -> (3,5),
    -> (3,6),
    -> (4,1)
    -> ;
ERROR 1062 (23000): Duplicate entry '1-2' for key 'PRIMARY'
mysql> insert into author2book(author_id,book_id) values
    -> (1,2),
    -> (1,2),
    -> (1,3),
    -> (1,4),
    -> (1,5),
    -> (2,1),
    -> (2,6),
    -> (3,4),
    -> (3,5),
    -> (3,6),
    -> (4,1)
    -> ;^C
mysql> insert into author2book(author_id,book_id) values
    -> (1,1),
    -> (1,2),
    -> (1,3),
    -> (1,4),
    -> (1,5),
    -> (2,1),
    -> (2,6),
    -> (3,4),
    -> (3,5),
    -> (3,6),
    -> (4,1)
    -> ;
Query OK, 11 rows affected (0.00 sec)
Records: 11  Duplicates: 0  Warnings: 0

mysql>

23-表關係之一對一

一、表關係之一對一;

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
    -> );
ERROR 1050 (42S01): Table 'customer' already exists
mysql>
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) on delete cascade on update cascade
    -> );
Query OK, 0 rows affected (0.01 sec)

mysql> desc student;
+-------------+-------------+------+-----+---------+----------------+
| Field       | Type        | Null | Key | Default | Extra          |
+-------------+-------------+------+-----+---------+----------------+
| id          | int(11)     | NO   | PRI | NULL    | auto_increment |
| class_name  | varchar(20) | NO   |     | NULL    |                |
| customer_id | int(11)     | YES  | UNI | NULL    |                |
+-------------+-------------+------+-----+---------+----------------+
3 rows in set (0.00 sec)

mysql> desc customer;
+-------+-------------+------+-----+---------+----------------+
| Field | Type        | Null | Key | Default | Extra          |
+-------+-------------+------+-----+---------+----------------+
| id    | int(11)     | NO   | PRI | NULL    | auto_increment |
| name  | varchar(20) | NO   |     | NULL    |                |
| qq    | varchar(10) | NO   |     | NULL    |                |
| phone | char(16)    | NO   |     | NULL    |                |
+-------+-------------+------+-----+---------+----------------+
4 rows in set (0.00 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.00 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.00 sec)
Records: 3  Duplicates: 0  Warnings: 0

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)

 
 

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>

24-記錄的增刪改查

一、插入數據INSERT;

1、插入完整數據(順序插入)
INSERT INTO 表名(字段1,字段2,字段3...字段n) VALUES(值1,值2,值3...值n);

INSERT INTO 表名 VALUES(值1,值2,值2...值n);



2、指定字段插入數據

INSERT INTO 表名(字段1,字段2,字段3...) VALUES (值1,值2,值3);



3、插入多條記錄

INSERT INTO 表名 VALUES 
(值1,值2,值3...值n),
(值1,值2,值3...值n),
(值1,值2,值3...值n);


4、插入查詢後的結果

INSERT INTO 表名 (字段1,字段2,字段3...字段n) SELECT (字段1,字段2,字段3...字段n) FROM 表2 WHERE XXX == 'XXXX';

二、更新數據UPDATE;

語法:
UPDATE 表名 SET 
    字段1 = 值1,
    字段2 = 值2,
    WHERE CONDITION(條件);

示例:
UPDATE mysql.user SET password = password('Ab123456.')
WHERE user = 'root' and host = 'localhost';

三、刪除數據DELETE;

語法:
 DELETE FROM 表名 WHERE CONDITION(條件);


示例:
    DELETE FROM mysql.user WHERE password = 'xxxx';

四、查詢數據SELECT;

小結:

對數據庫的操做,查詢語句居多;

一、單表查詢;

select distinct 字段1,字段2,字段3  from 庫名.表名 where 條件 group by 分組條件 having 過濾 order by 排序 limit 限制條數;

二、多表查詢;

三、查詢經過步驟;

 

一、找到帶查詢的表名:from
二、拿着where指定的約束條件,去文件/表中取出一條條記錄
3、將取出的一條條記錄進行分組group by ,若是沒有group by,則總體做爲一組
4、將分組的結果進行having 過濾
5、執行select
6、進行distinct去重
7、將結果按照條件排序order by(默認asc,指定desc)
八、限制結果的顯示條數

 

25-簡單查詢

一、表設計;

company.employee
    員工id      id                  int             
    姓名        emp_name            varchar
    性別        sex                 enum
    年齡        age                 int
    入職日期     hire_date           date
    崗位        post                varchar
    職位描述     post_comment        varchar
    薪水        salary              double
    辦公室       office              int
    部門編號     depart_id           int

二、查詢場景舉例;

  • 單字段簡單查詢;
  • 多字段組合查詢,逗號分隔字段名稱,as起個別名;
  • 避免重複DISTINCT
  • 經過四則運算查詢
  • CONCAT()定義顯示格式(類Python中的格式化輸出)

三、操做日誌;

Enter password: ************
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 37
Server version: 5.7.20-log MySQL Community Server (GPL)

Copyright (c) 2000, 2017, 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> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| engines            |
| luffycity          |
| mysql              |
| performance_schema |
| sakila             |
| sys                |
| world              |
+--------------------+
8 rows in set (0.00 sec)

mysql> create database luffy_practise charset utf8;
Query OK, 1 row affected (0.00 sec)

mysql> show create database luffy_practise;
+----------------+-------------------------------------------------------------------------+
| Database       | Create Database                                                         |
+----------------+-------------------------------------------------------------------------+
| luffy_practise | CREATE DATABASE `luffy_practise` /*!40100 DEFAULT CHARACTER SET utf8 */ |
+----------------+-------------------------------------------------------------------------+
1 row in set (0.00 sec)

mysql> use luffy_practise;
Database changed
mysql> create table employee(
    -> id int not null unique auto_increment,
    -> name varchar(20) not null,
    -> sex enum('male','female') not null default 'male',
    -> age int(3) unsigned not null default 28,
    -> hire_date date not null,
    -> post_comment varchar(100),
    -> salary double(15,2),
    -> office int,
    -> depart_id int
    -> );
Query OK, 0 rows affected (0.01 sec)

mysql> desc employee;
+--------------+-----------------------+------+-----+---------+----------------+
| Field        | Type                  | Null | Key | Default | Extra          |
+--------------+-----------------------+------+-----+---------+----------------+
| id           | int(11)               | NO   | PRI | NULL    | auto_increment |
| name         | varchar(20)           | NO   |     | NULL    |                |
| sex          | enum('male','female') | NO   |     | male    |                |
| age          | int(3) unsigned       | NO   |     | 28      |                |
| hire_date    | date                  | NO   |     | NULL    |                |
| post_comment | varchar(100)          | YES  |     | NULL    |                |
| salary       | double(15,2)          | YES  |     | NULL    |                |
| office       | int(11)               | YES  |     | NULL    |                |
| depart_id    | int(11)               | YES  |     | NULL    |                |
+--------------+-----------------------+------+-----+---------+----------------+
9 rows in set (0.00 sec)

mysql> alter table add post varchar(50) after hire_date;
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 'add post varchar(50) after hire_date' at line 1
mysql> alter table employee  add post varchar(50) after hire_date;
Query OK, 0 rows affected (0.03 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> desc employee;
+--------------+-----------------------+------+-----+---------+----------------+
| Field        | Type                  | Null | Key | Default | Extra          |
+--------------+-----------------------+------+-----+---------+----------------+
| id           | int(11)               | NO   | PRI | NULL    | auto_increment |
| name         | varchar(20)           | NO   |     | NULL    |                |
| sex          | enum('male','female') | NO   |     | male    |                |
| age          | int(3) unsigned       | NO   |     | 28      |                |
| hire_date    | date                  | NO   |     | NULL    |                |
| post         | varchar(50)           | YES  |     | NULL    |                |
| post_comment | varchar(100)          | YES  |     | NULL    |                |
| salary       | double(15,2)          | YES  |     | NULL    |                |
| office       | int(11)               | YES  |     | NULL    |                |
| depart_id    | int(11)               | YES  |     | NULL    |                |
+--------------+-----------------------+------+-----+---------+----------------+
10 rows in set (0.00 sec)

mysql> insert into employee(name,sex,age,hire_date,post,salary,office,depart_id) values
    -> ('egon','male',18,'20170301','老男孩駐沙河辦事處外交大使',7300.33,401,1),
    -> ('alex','male',78,'20150302','teacher',1000000.31,401,1),
    -> ('wupeiqi','male',81,'20130305','teacher',8300,401,1),
    -> ('yuanhao','male',73,'20140701','teacher',3500,401,1),
    -> ('liwenzhou','male',28,'20121101','teacher',2100,401,1),
    -> ('jingliyang','female',18,'20110211','teacher',9000,401,1),
    -> ('jinxin','male',18,'19000301','teacher',30000,401,1),
    -> ('成龍','male',48,'20101111','teacher',10000,401,1),
    ->
    -> ('歪歪','female',48,'20150311','sale',3000.13,402,2),
    -> ('丫丫','female',38,'20101101','sale',2000.35,402,2),
    -> ('丁丁','female',18,'20110312','sale',1000.37,402,2),
    -> ('星星','female',18,'20160513','sale',3000.29,402,2),
    -> ('格格','female',28,'20170127','sale',4000.33,402,2),
    ->
    -> ('張野','male',28,'20160311','operation',10000.13,403,3),
    -> ('程咬金','male',18,'19970312','operation',20000,403,3),
    -> ('程咬銀','female',18,'20130311','operation',19000,403,3),
    -> ('程咬銅','male',18,'20150411','operation',18000,403,3),
    -> ('程咬鐵','female',18,'20140512','operation',17000,403,3)
    -> ;
Query OK, 18 rows affected (0.00 sec)
Records: 18  Duplicates: 0  Warnings: 0

mysql> select * from employee;
+----+------------+--------+-----+------------+-----------------------------------------+--------------+------------+--------+-----------+
| id | name       | sex    | age | hire_date  | post                                    | post_comment | salary     | office | depart_id |
+----+------------+--------+-----+------------+-----------------------------------------+--------------+------------+--------+-----------+
|  1 | egon       | male   |  18 | 2017-03-01 | 老男孩駐沙河辦事處外交大使              | NULL         |    7300.33 |    401 |         1 |
|  2 | alex       | male   |  78 | 2015-03-02 | teacher                                 | NULL         | 1000000.31 |    401 |         1 |
|  3 | wupeiqi    | male   |  81 | 2013-03-05 | teacher                                 | NULL         |    8300.00 |    401 |         1 |
|  4 | yuanhao    | male   |  73 | 2014-07-01 | teacher                                 | NULL         |    3500.00 |    401 |         1 |
|  5 | liwenzhou  | male   |  28 | 2012-11-01 | teacher                                 | NULL         |    2100.00 |    401 |         1 |
|  6 | jingliyang | female |  18 | 2011-02-11 | teacher                                 | NULL         |    9000.00 |    401 |         1 |
|  7 | jinxin     | male   |  18 | 1900-03-01 | teacher                                 | NULL         |   30000.00 |    401 |         1 |
|  8 | 成龍       | male   |  48 | 2010-11-11 | teacher                                 | NULL         |   10000.00 |    401 |         1 |
|  9 | 歪歪       | female |  48 | 2015-03-11 | sale                                    | NULL         |    3000.13 |    402 |         2 |
| 10 | 丫丫       | female |  38 | 2010-11-01 | sale                                    | NULL         |    2000.35 |    402 |         2 |
| 11 | 丁丁       | female |  18 | 2011-03-12 | sale                                    | NULL         |    1000.37 |    402 |         2 |
| 12 | 星星       | female |  18 | 2016-05-13 | sale                                    | NULL         |    3000.29 |    402 |         2 |
| 13 | 格格       | female |  28 | 2017-01-27 | sale                                    | NULL         |    4000.33 |    402 |         2 |
| 14 | 張野       | male   |  28 | 2016-03-11 | operation                               | NULL         |   10000.13 |    403 |         3 |
| 15 | 程咬金     | male   |  18 | 1997-03-12 | operation                               | NULL         |   20000.00 |    403 |         3 |
| 16 | 程咬銀     | female |  18 | 2013-03-11 | operation                               | NULL         |   19000.00 |    403 |         3 |
| 17 | 程咬銅     | male   |  18 | 2015-04-11 | operation                               | NULL         |   18000.00 |    403 |         3 |
| 18 | 程咬鐵     | female |  18 | 2014-05-12 | operation                               | NULL         |   17000.00 |    403 |         3 |
+----+------------+--------+-----+------------+-----------------------------------------+--------------+------------+--------+-----------+
18 rows in set (0.00 sec)

mysql> select id,name,sex,age,hire_date,post_comment,salary,office,depart_id from employee;
+----+------------+--------+-----+------------+--------------+------------+--------+-----------+
| id | name       | sex    | age | hire_date  | post_comment | salary     | office | depart_id |
+----+------------+--------+-----+------------+--------------+------------+--------+-----------+
|  1 | egon       | male   |  18 | 2017-03-01 | NULL         |    7300.33 |    401 |         1 |
|  2 | alex       | male   |  78 | 2015-03-02 | NULL         | 1000000.31 |    401 |         1 |
|  3 | wupeiqi    | male   |  81 | 2013-03-05 | NULL         |    8300.00 |    401 |         1 |
|  4 | yuanhao    | male   |  73 | 2014-07-01 | NULL         |    3500.00 |    401 |         1 |
|  5 | liwenzhou  | male   |  28 | 2012-11-01 | NULL         |    2100.00 |    401 |         1 |
|  6 | jingliyang | female |  18 | 2011-02-11 | NULL         |    9000.00 |    401 |         1 |
|  7 | jinxin     | male   |  18 | 1900-03-01 | NULL         |   30000.00 |    401 |         1 |
|  8 | 成龍       | male   |  48 | 2010-11-11 | NULL         |   10000.00 |    401 |         1 |
|  9 | 歪歪       | female |  48 | 2015-03-11 | NULL         |    3000.13 |    402 |         2 |
| 10 | 丫丫       | female |  38 | 2010-11-01 | NULL         |    2000.35 |    402 |         2 |
| 11 | 丁丁       | female |  18 | 2011-03-12 | NULL         |    1000.37 |    402 |         2 |
| 12 | 星星       | female |  18 | 2016-05-13 | NULL         |    3000.29 |    402 |         2 |
| 13 | 格格       | female |  28 | 2017-01-27 | NULL         |    4000.33 |    402 |         2 |
| 14 | 張野       | male   |  28 | 2016-03-11 | NULL         |   10000.13 |    403 |         3 |
| 15 | 程咬金     | male   |  18 | 1997-03-12 | NULL         |   20000.00 |    403 |         3 |
| 16 | 程咬銀     | female |  18 | 2013-03-11 | NULL         |   19000.00 |    403 |         3 |
| 17 | 程咬銅     | male   |  18 | 2015-04-11 | NULL         |   18000.00 |    403 |         3 |
| 18 | 程咬鐵     | female |  18 | 2014-05-12 | NULL         |   17000.00 |    403 |         3 |
+----+------------+--------+-----+------------+--------------+------------+--------+-----------+
18 rows in set (0.00 sec)

mysql> select id,name,sex from employee;
+----+------------+--------+
| id | name       | sex    |
+----+------------+--------+
|  1 | egon       | male   |
|  2 | alex       | male   |
|  3 | wupeiqi    | male   |
|  4 | yuanhao    | male   |
|  5 | liwenzhou  | male   |
|  6 | jingliyang | female |
|  7 | jinxin     | male   |
|  8 | 成龍       | male   |
|  9 | 歪歪       | female |
| 10 | 丫丫       | female |
| 11 | 丁丁       | female |
| 12 | 星星       | female |
| 13 | 格格       | female |
| 14 | 張野       | male   |
| 15 | 程咬金     | male   |
| 16 | 程咬銀     | female |
| 17 | 程咬銅     | male   |
| 18 | 程咬鐵     | female |
+----+------------+--------+
18 rows in set (0.00 sec)

mysql> select distinct id,name,name,age,sex from employee;
+----+------------+------------+-----+--------+
| id | name       | name       | age | sex    |
+----+------------+------------+-----+--------+
|  1 | egon       | egon       |  18 | male   |
|  2 | alex       | alex       |  78 | male   |
|  3 | wupeiqi    | wupeiqi    |  81 | male   |
|  4 | yuanhao    | yuanhao    |  73 | male   |
|  5 | liwenzhou  | liwenzhou  |  28 | male   |
|  6 | jingliyang | jingliyang |  18 | female |
|  7 | jinxin     | jinxin     |  18 | male   |
|  8 | 成龍       | 成龍       |  48 | male   |
|  9 | 歪歪       | 歪歪       |  48 | female |
| 10 | 丫丫       | 丫丫       |  38 | female |
| 11 | 丁丁       | 丁丁       |  18 | female |
| 12 | 星星       | 星星       |  18 | female |
| 13 | 格格       | 格格       |  28 | female |
| 14 | 張野       | 張野       |  28 | male   |
| 15 | 程咬金     | 程咬金     |  18 | male   |
| 16 | 程咬銀     | 程咬銀     |  18 | female |
| 17 | 程咬銅     | 程咬銅     |  18 | male   |
| 18 | 程咬鐵     | 程咬鐵     |  18 | female |
+----+------------+------------+-----+--------+
18 rows in set (0.00 sec)

mysql> select distinct post from employee;
+-----------------------------------------+
| post                                    |
+-----------------------------------------+
| 老男孩駐沙河辦事處外交大使              |
| teacher                                 |
| sale                                    |
| operation                               |
+-----------------------------------------+
4 rows in set (0.00 sec)

mysql> select  post from employee;
+-----------------------------------------+
| post                                    |
+-----------------------------------------+
| 老男孩駐沙河辦事處外交大使              |
| teacher                                 |
| teacher                                 |
| teacher                                 |
| teacher                                 |
| teacher                                 |
| teacher                                 |
| teacher                                 |
| sale                                    |
| sale                                    |
| sale                                    |
| sale                                    |
| sale                                    |
| operation                               |
| operation                               |
| operation                               |
| operation                               |
| operation                               |
+-----------------------------------------+
18 rows in set (0.00 sec)

mysql> select distinct post from employee;
+-----------------------------------------+
| post                                    |
+-----------------------------------------+
| 老男孩駐沙河辦事處外交大使              |
| teacher                                 |
| sale                                    |
| operation                               |
+-----------------------------------------+
4 rows in set (0.00 sec)

mysql> select * from employee;
+----+------------+--------+-----+------------+-----------------------------------------+--------------+------------+--------+-----------+
| id | name       | sex    | age | hire_date  | post                                    | post_comment | salary     | office | depart_id |
+----+------------+--------+-----+------------+-----------------------------------------+--------------+------------+--------+-----------+
|  1 | egon       | male   |  18 | 2017-03-01 | 老男孩駐沙河辦事處外交大使              | NULL         |    7300.33 |    401 |         1 |
|  2 | alex       | male   |  78 | 2015-03-02 | teacher                                 | NULL         | 1000000.31 |    401 |         1 |
|  3 | wupeiqi    | male   |  81 | 2013-03-05 | teacher                                 | NULL         |    8300.00 |    401 |         1 |
|  4 | yuanhao    | male   |  73 | 2014-07-01 | teacher                                 | NULL         |    3500.00 |    401 |         1 |
|  5 | liwenzhou  | male   |  28 | 2012-11-01 | teacher                                 | NULL         |    2100.00 |    401 |         1 |
|  6 | jingliyang | female |  18 | 2011-02-11 | teacher                                 | NULL         |    9000.00 |    401 |         1 |
|  7 | jinxin     | male   |  18 | 1900-03-01 | teacher                                 | NULL         |   30000.00 |    401 |         1 |
|  8 | 成龍       | male   |  48 | 2010-11-11 | teacher                                 | NULL         |   10000.00 |    401 |         1 |
|  9 | 歪歪       | female |  48 | 2015-03-11 | sale                                    | NULL         |    3000.13 |    402 |         2 |
| 10 | 丫丫       | female |  38 | 2010-11-01 | sale                                    | NULL         |    2000.35 |    402 |         2 |
| 11 | 丁丁       | female |  18 | 2011-03-12 | sale                                    | NULL         |    1000.37 |    402 |         2 |
| 12 | 星星       | female |  18 | 2016-05-13 | sale                                    | NULL         |    3000.29 |    402 |         2 |
| 13 | 格格       | female |  28 | 2017-01-27 | sale                                    | NULL         |    4000.33 |    402 |         2 |
| 14 | 張野       | male   |  28 | 2016-03-11 | operation                               | NULL         |   10000.13 |    403 |         3 |
| 15 | 程咬金     | male   |  18 | 1997-03-12 | operation                               | NULL         |   20000.00 |    403 |         3 |
| 16 | 程咬銀     | female |  18 | 2013-03-11 | operation                               | NULL         |   19000.00 |    403 |         3 |
| 17 | 程咬銅     | male   |  18 | 2015-04-11 | operation                               | NULL         |   18000.00 |    403 |         3 |
| 18 | 程咬鐵     | female |  18 | 2014-05-12 | operation                               | NULL         |   17000.00 |    403 |         3 |
+----+------------+--------+-----+------------+-----------------------------------------+--------------+------------+--------+-----------+
18 rows in set (0.00 sec)

mysql> select name,salary from employee;
+------------+------------+
| name       | salary     |
+------------+------------+
| egon       |    7300.33 |
| alex       | 1000000.31 |
| wupeiqi    |    8300.00 |
| yuanhao    |    3500.00 |
| liwenzhou  |    2100.00 |
| jingliyang |    9000.00 |
| jinxin     |   30000.00 |
| 成龍       |   10000.00 |
| 歪歪       |    3000.13 |
| 丫丫       |    2000.35 |
| 丁丁       |    1000.37 |
| 星星       |    3000.29 |
| 格格       |    4000.33 |
| 張野       |   10000.13 |
| 程咬金     |   20000.00 |
| 程咬銀     |   19000.00 |
| 程咬銅     |   18000.00 |
| 程咬鐵     |   17000.00 |
+------------+------------+
18 rows in set (0.00 sec)

mysql> select name,salary*12 from employee;
+------------+-------------+
| name       | salary*12   |
+------------+-------------+
| egon       |    87603.96 |
| alex       | 12000003.72 |
| wupeiqi    |    99600.00 |
| yuanhao    |    42000.00 |
| liwenzhou  |    25200.00 |
| jingliyang |   108000.00 |
| jinxin     |   360000.00 |
| 成龍       |   120000.00 |
| 歪歪       |    36001.56 |
| 丫丫       |    24004.20 |
| 丁丁       |    12004.44 |
| 星星       |    36003.48 |
| 格格       |    48003.96 |
| 張野       |   120001.56 |
| 程咬金     |   240000.00 |
| 程咬銀     |   228000.00 |
| 程咬銅     |   216000.00 |
| 程咬鐵     |   204000.00 |
+------------+-------------+
18 rows in set (0.00 sec)

mysql> select name,salary*12 as annunal_salary from employee;
+------------+----------------+
| name       | annunal_salary |
+------------+----------------+
| egon       |       87603.96 |
| alex       |    12000003.72 |
| wupeiqi    |       99600.00 |
| yuanhao    |       42000.00 |
| liwenzhou  |       25200.00 |
| jingliyang |      108000.00 |
| jinxin     |      360000.00 |
| 成龍       |      120000.00 |
| 歪歪       |       36001.56 |
| 丫丫       |       24004.20 |
| 丁丁       |       12004.44 |
| 星星       |       36003.48 |
| 格格       |       48003.96 |
| 張野       |      120001.56 |
| 程咬金     |      240000.00 |
| 程咬銀     |      228000.00 |
| 程咬銅     |      216000.00 |
| 程咬鐵     |      204000.00 |
+------------+----------------+
18 rows in set (0.00 sec)

mysql> select * from employee;
+----+------------+--------+-----+------------+-----------------------------------------+--------------+------------+--------+-----------+
| id | name       | sex    | age | hire_date  | post                                    | post_comment | salary     | office | depart_id |
+----+------------+--------+-----+------------+-----------------------------------------+--------------+------------+--------+-----------+
|  1 | egon       | male   |  18 | 2017-03-01 | 老男孩駐沙河辦事處外交大使              | NULL         |    7300.33 |    401 |         1 |
|  2 | alex       | male   |  78 | 2015-03-02 | teacher                                 | NULL         | 1000000.31 |    401 |         1 |
|  3 | wupeiqi    | male   |  81 | 2013-03-05 | teacher                                 | NULL         |    8300.00 |    401 |         1 |
|  4 | yuanhao    | male   |  73 | 2014-07-01 | teacher                                 | NULL         |    3500.00 |    401 |         1 |
|  5 | liwenzhou  | male   |  28 | 2012-11-01 | teacher                                 | NULL         |    2100.00 |    401 |         1 |
|  6 | jingliyang | female |  18 | 2011-02-11 | teacher                                 | NULL         |    9000.00 |    401 |         1 |
|  7 | jinxin     | male   |  18 | 1900-03-01 | teacher                                 | NULL         |   30000.00 |    401 |         1 |
|  8 | 成龍       | male   |  48 | 2010-11-11 | teacher                                 | NULL         |   10000.00 |    401 |         1 |
|  9 | 歪歪       | female |  48 | 2015-03-11 | sale                                    | NULL         |    3000.13 |    402 |         2 |
| 10 | 丫丫       | female |  38 | 2010-11-01 | sale                                    | NULL         |    2000.35 |    402 |         2 |
| 11 | 丁丁       | female |  18 | 2011-03-12 | sale                                    | NULL         |    1000.37 |    402 |         2 |
| 12 | 星星       | female |  18 | 2016-05-13 | sale                                    | NULL         |    3000.29 |    402 |         2 |
| 13 | 格格       | female |  28 | 2017-01-27 | sale                                    | NULL         |    4000.33 |    402 |         2 |
| 14 | 張野       | male   |  28 | 2016-03-11 | operation                               | NULL         |   10000.13 |    403 |         3 |
| 15 | 程咬金     | male   |  18 | 1997-03-12 | operation                               | NULL         |   20000.00 |    403 |         3 |
| 16 | 程咬銀     | female |  18 | 2013-03-11 | operation                               | NULL         |   19000.00 |    403 |         3 |
| 17 | 程咬銅     | male   |  18 | 2015-04-11 | operation                               | NULL         |   18000.00 |    403 |         3 |
| 18 | 程咬鐵     | female |  18 | 2014-05-12 | operation                               | NULL         |   17000.00 |    403 |         3 |
+----+------------+--------+-----+------------+-----------------------------------------+--------------+------------+--------+-----------+
18 rows in set (0.00 sec)

mysql> select concat('姓名:',name,'年薪:',salary*12) AS Annual_salary from employee;
+-----------------------------------+
| Annual_salary                     |
+-----------------------------------+
| 姓名:egon年薪:87603.96            |
| 姓名:alex年薪:12000003.72         |
| 姓名:wupeiqi年薪:99600.00         |
| 姓名:yuanhao年薪:42000.00         |
| 姓名:liwenzhou年薪:25200.00       |
| 姓名:jingliyang年薪:108000.00     |
| 姓名:jinxin年薪:360000.00         |
| 姓名:成龍年薪:120000.00           |
| 姓名:歪歪年薪:36001.56            |
| 姓名:丫丫年薪:24004.20            |
| 姓名:丁丁年薪:12004.44            |
| 姓名:星星年薪:36003.48            |
| 姓名:格格年薪:48003.96            |
| 姓名:張野年薪:120001.56           |
| 姓名:程咬金年薪:240000.00         |
| 姓名:程咬銀年薪:228000.00         |
| 姓名:程咬銅年薪:216000.00         |
| 姓名:程咬鐵年薪:204000.00         |
+-----------------------------------+
18 rows in set (0.00 sec)

mysql> select concat ws(':',name,age,salary) from employee;
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 '(':',name,age,salary) from employee' at line 1
mysql> select concat ws(':',name,age,salary) from employee;
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 '(':',name,age,salary) from employee' at line 1
mysql> select concat ws(':',name,age) from employee;
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 '(':',name,age) from employee' at line 1
mysql> select concat_ws(':',name,age) from employee;
+-------------------------+
| concat_ws(':',name,age) |
+-------------------------+
| egon:18                 |
| alex:78                 |
| wupeiqi:81              |
| yuanhao:73              |
| liwenzhou:28            |
| jingliyang:18           |
| jinxin:18               |
| 成龍:48                 |
| 歪歪:48                 |
| 丫丫:38                 |
| 丁丁:18                 |
| 星星:18                 |
| 格格:28                 |
| 張野:28                 |
| 程咬金:18               |
| 程咬銀:18               |
| 程咬銅:18               |
| 程咬鐵:18               |
+-------------------------+
18 rows in set (0.00 sec)

mysql> select concat('<薪資:',salary,'>') from employee;
+-------------------------------+
| concat('<薪資:',salary,'>')   |
+-------------------------------+
| <薪資:7300.33>                |
| <薪資:1000000.31>             |
| <薪資:8300.00>                |
| <薪資:3500.00>                |
| <薪資:2100.00>                |
| <薪資:9000.00>                |
| <薪資:30000.00>               |
| <薪資:10000.00>               |
| <薪資:3000.13>                |
| <薪資:2000.35>                |
| <薪資:1000.37>                |
| <薪資:3000.29>                |
| <薪資:4000.33>                |
| <薪資:10000.13>               |
| <薪資:20000.00>               |
| <薪資:19000.00>               |
| <薪資:18000.00>               |
| <薪資:17000.00>               |
+-------------------------------+
18 rows in set (0.00 sec)

mysql> select concat('<薪資:',salary,'>'),concat('<姓名:',name,'>') from employee;
+-------------------------------+-----------------------------+
| concat('<薪資:',salary,'>')   | concat('<姓名:',name,'>')   |
+-------------------------------+-----------------------------+
| <薪資:7300.33>                | <姓名:egon>                 |
| <薪資:1000000.31>             | <姓名:alex>                 |
| <薪資:8300.00>                | <姓名:wupeiqi>              |
| <薪資:3500.00>                | <姓名:yuanhao>              |
| <薪資:2100.00>                | <姓名:liwenzhou>            |
| <薪資:9000.00>                | <姓名:jingliyang>           |
| <薪資:30000.00>               | <姓名:jinxin>               |
| <薪資:10000.00>               | <姓名:成龍>                 |
| <薪資:3000.13>                | <姓名:歪歪>                 |
| <薪資:2000.35>                | <姓名:丫丫>                 |
| <薪資:1000.37>                | <姓名:丁丁>                 |
| <薪資:3000.29>                | <姓名:星星>                 |
| <薪資:4000.33>                | <姓名:格格>                 |
| <薪資:10000.13>               | <姓名:張野>                 |
| <薪資:20000.00>               | <姓名:程咬金>               |
| <薪資:19000.00>               | <姓名:程咬銀>               |
| <薪資:18000.00>               | <姓名:程咬銅>               |
| <薪資:17000.00>               | <姓名:程咬鐵>               |
+-------------------------------+-----------------------------+
18 rows in set (0.00 sec)

mysql> desc employee;
+--------------+-----------------------+------+-----+---------+----------------+
| Field        | Type                  | Null | Key | Default | Extra          |
+--------------+-----------------------+------+-----+---------+----------------+
| id           | int(11)               | NO   | PRI | NULL    | auto_increment |
| name         | varchar(20)           | NO   |     | NULL    |                |
| sex          | enum('male','female') | NO   |     | male    |                |
| age          | int(3) unsigned       | NO   |     | 28      |                |
| hire_date    | date                  | NO   |     | NULL    |                |
| post         | varchar(50)           | YES  |     | NULL    |                |
| post_comment | varchar(100)          | YES  |     | NULL    |                |
| salary       | double(15,2)          | YES  |     | NULL    |                |
| office       | int(11)               | YES  |     | NULL    |                |
| depart_id    | int(11)               | YES  |     | NULL    |                |
+--------------+-----------------------+------+-----+---------+----------------+
10 rows in set (0.00 sec)

mysql> select distinct post from employee;
+-----------------------------------------+
| post                                    |
+-----------------------------------------+
| 老男孩駐沙河辦事處外交大使              |
| teacher                                 |
| sale                                    |
| operation                               |
+-----------------------------------------+
4 rows in set (0.00 sec)

mysql> select name,salary*12 as annual_year from employee;
+------------+-------------+
| name       | annual_year |
+------------+-------------+
| egon       |    87603.96 |
| alex       | 12000003.72 |
| wupeiqi    |    99600.00 |
| yuanhao    |    42000.00 |
| liwenzhou  |    25200.00 |
| jingliyang |   108000.00 |
| jinxin     |   360000.00 |
| 成龍       |   120000.00 |
| 歪歪       |    36001.56 |
| 丫丫       |    24004.20 |
| 丁丁       |    12004.44 |
| 星星       |    36003.48 |
| 格格       |    48003.96 |
| 張野       |   120001.56 |
| 程咬金     |   240000.00 |
| 程咬銀     |   228000.00 |
| 程咬銅     |   216000.00 |
| 程咬鐵     |   204000.00 |
+------------+-------------+
18 rows in set (0.00 sec)

mysql>

26-where約束

一、where條件的查詢邏輯;

  • 比較運算符:>、<、>=、<=、<>、!=
  • between 80 and 100,值在10~20之間;
  • in (80,91,20)值是80、91或者20
  • like 'cuixiaozha%',%表明任意多個字符,_表示一個字符;
  • 邏輯運算符,在多個條件中能夠直接使用邏輯運算符and or not

二、常見的查詢場景;

  • 單條件查詢;
  • 多條件組合查詢;
  • 關鍵字BETWEEN AND;
  • 關鍵字 IS NULL (判斷某個字段是否爲NULL不能用等號,要使用IS),其中,''是空字符串而不是NULL
  • 關鍵字IN集合查詢;
  • 關鍵字LIKE模糊查詢(通配符%,通配符_);

三、操做日誌;

Enter password: ************
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 38
Server version: 5.7.20-log MySQL Community Server (GPL)

Copyright (c) 2000, 2017, 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> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| engines            |
| luffy_practise     |
| luffycity          |
| mysql              |
| performance_schema |
| sakila             |
| sys                |
| world              |
+--------------------+
9 rows in set (0.01 sec)

mysql> use luffy_practise;
Database changed
mysql> show tables;
+--------------------------+
| Tables_in_luffy_practise |
+--------------------------+
| employee                 |
+--------------------------+
1 row in set (0.00 sec)

mysql> select * from employee;
+----+------------+--------+-----+------------+-----------------------------------------+--------------+------------+--------+-----------+
| id | name       | sex    | age | hire_date  | post                                    | post_comment | salary     | office | depart_id |
+----+------------+--------+-----+------------+-----------------------------------------+--------------+------------+--------+-----------+
|  1 | egon       | male   |  18 | 2017-03-01 | 老男孩駐沙河辦事處外交大使              | NULL         |    7300.33 |    401 |         1 |
|  2 | alex       | male   |  78 | 2015-03-02 | teacher                                 | NULL         | 1000000.31 |    401 |         1 |
|  3 | wupeiqi    | male   |  81 | 2013-03-05 | teacher                                 | NULL         |    8300.00 |    401 |         1 |
|  4 | yuanhao    | male   |  73 | 2014-07-01 | teacher                                 | NULL         |    3500.00 |    401 |         1 |
|  5 | liwenzhou  | male   |  28 | 2012-11-01 | teacher                                 | NULL         |    2100.00 |    401 |         1 |
|  6 | jingliyang | female |  18 | 2011-02-11 | teacher                                 | NULL         |    9000.00 |    401 |         1 |
|  7 | jinxin     | male   |  18 | 1900-03-01 | teacher                                 | NULL         |   30000.00 |    401 |         1 |
|  8 | 成龍       | male   |  48 | 2010-11-11 | teacher                                 | NULL         |   10000.00 |    401 |         1 |
|  9 | 歪歪       | female |  48 | 2015-03-11 | sale                                    | NULL         |    3000.13 |    402 |         2 |
| 10 | 丫丫       | female |  38 | 2010-11-01 | sale                                    | NULL         |    2000.35 |    402 |         2 |
| 11 | 丁丁       | female |  18 | 2011-03-12 | sale                                    | NULL         |    1000.37 |    402 |         2 |
| 12 | 星星       | female |  18 | 2016-05-13 | sale                                    | NULL         |    3000.29 |    402 |         2 |
| 13 | 格格       | female |  28 | 2017-01-27 | sale                                    | NULL         |    4000.33 |    402 |         2 |
| 14 | 張野       | male   |  28 | 2016-03-11 | operation                               | NULL         |   10000.13 |    403 |         3 |
| 15 | 程咬金     | male   |  18 | 1997-03-12 | operation                               | NULL         |   20000.00 |    403 |         3 |
| 16 | 程咬銀     | female |  18 | 2013-03-11 | operation                               | NULL         |   19000.00 |    403 |         3 |
| 17 | 程咬銅     | male   |  18 | 2015-04-11 | operation                               | NULL         |   18000.00 |    403 |         3 |
| 18 | 程咬鐵     | female |  18 | 2014-05-12 | operation                               | NULL         |   17000.00 |    403 |         3 |
+----+------------+--------+-----+------------+-----------------------------------------+--------------+------------+--------+-----------+
18 rows in set (0.01 sec)

mysql> select * from employee where id >7;
+----+-----------+--------+-----+------------+-----------+--------------+----------+--------+-----------+
| id | name      | sex    | age | hire_date  | post      | post_comment | salary   | office | depart_id |
+----+-----------+--------+-----+------------+-----------+--------------+----------+--------+-----------+
|  8 | 成龍      | male   |  48 | 2010-11-11 | teacher   | NULL         | 10000.00 |    401 |         1 |
|  9 | 歪歪      | female |  48 | 2015-03-11 | sale      | NULL         |  3000.13 |    402 |         2 |
| 10 | 丫丫      | female |  38 | 2010-11-01 | sale      | NULL         |  2000.35 |    402 |         2 |
| 11 | 丁丁      | female |  18 | 2011-03-12 | sale      | NULL         |  1000.37 |    402 |         2 |
| 12 | 星星      | female |  18 | 2016-05-13 | sale      | NULL         |  3000.29 |    402 |         2 |
| 13 | 格格      | female |  28 | 2017-01-27 | sale      | NULL         |  4000.33 |    402 |         2 |
| 14 | 張野      | male   |  28 | 2016-03-11 | operation | NULL         | 10000.13 |    403 |         3 |
| 15 | 程咬金    | male   |  18 | 1997-03-12 | operation | NULL         | 20000.00 |    403 |         3 |
| 16 | 程咬銀    | female |  18 | 2013-03-11 | operation | NULL         | 19000.00 |    403 |         3 |
| 17 | 程咬銅    | male   |  18 | 2015-04-11 | operation | NULL         | 18000.00 |    403 |         3 |
| 18 | 程咬鐵    | female |  18 | 2014-05-12 | operation | NULL         | 17000.00 |    403 |         3 |
+----+-----------+--------+-----+------------+-----------+--------------+----------+--------+-----------+
11 rows in set (0.00 sec)

mysql> select id,name from employee where id >7;
+----+-----------+
| id | name      |
+----+-----------+
|  8 | 成龍      |
|  9 | 歪歪      |
| 10 | 丫丫      |
| 11 | 丁丁      |
| 12 | 星星      |
| 13 | 格格      |
| 14 | 張野      |
| 15 | 程咬金    |
| 16 | 程咬銀    |
| 17 | 程咬銅    |
| 18 | 程咬鐵    |
+----+-----------+
11 rows in set (0.00 sec)

mysql> select name,salary  from employee where post = 'teacher' and salary > 8000;
+------------+------------+
| name       | salary     |
+------------+------------+
| alex       | 1000000.31 |
| wupeiqi    |    8300.00 |
| jingliyang |    9000.00 |
| jinxin     |   30000.00 |
| 成龍       |   10000.00 |
+------------+------------+
5 rows in set (0.00 sec)

mysql> select * from employee;
+----+------------+--------+-----+------------+-----------------------------------------+--------------+------------+--------+-----------+
| id | name       | sex    | age | hire_date  | post                                    | post_comment | salary     | office | depart_id |
+----+------------+--------+-----+------------+-----------------------------------------+--------------+------------+--------+-----------+
|  1 | egon       | male   |  18 | 2017-03-01 | 老男孩駐沙河辦事處外交大使              | NULL         |    7300.33 |    401 |         1 |
|  2 | alex       | male   |  78 | 2015-03-02 | teacher                                 | NULL         | 1000000.31 |    401 |         1 |
|  3 | wupeiqi    | male   |  81 | 2013-03-05 | teacher                                 | NULL         |    8300.00 |    401 |         1 |
|  4 | yuanhao    | male   |  73 | 2014-07-01 | teacher                                 | NULL         |    3500.00 |    401 |         1 |
|  5 | liwenzhou  | male   |  28 | 2012-11-01 | teacher                                 | NULL         |    2100.00 |    401 |         1 |
|  6 | jingliyang | female |  18 | 2011-02-11 | teacher                                 | NULL         |    9000.00 |    401 |         1 |
|  7 | jinxin     | male   |  18 | 1900-03-01 | teacher                                 | NULL         |   30000.00 |    401 |         1 |
|  8 | 成龍       | male   |  48 | 2010-11-11 | teacher                                 | NULL         |   10000.00 |    401 |         1 |
|  9 | 歪歪       | female |  48 | 2015-03-11 | sale                                    | NULL         |    3000.13 |    402 |         2 |
| 10 | 丫丫       | female |  38 | 2010-11-01 | sale                                    | NULL         |    2000.35 |    402 |         2 |
| 11 | 丁丁       | female |  18 | 2011-03-12 | sale                                    | NULL         |    1000.37 |    402 |         2 |
| 12 | 星星       | female |  18 | 2016-05-13 | sale                                    | NULL         |    3000.29 |    402 |         2 |
| 13 | 格格       | female |  28 | 2017-01-27 | sale                                    | NULL         |    4000.33 |    402 |         2 |
| 14 | 張野       | male   |  28 | 2016-03-11 | operation                               | NULL         |   10000.13 |    403 |         3 |
| 15 | 程咬金     | male   |  18 | 1997-03-12 | operation                               | NULL         |   20000.00 |    403 |         3 |
| 16 | 程咬銀     | female |  18 | 2013-03-11 | operation                               | NULL         |   19000.00 |    403 |         3 |
| 17 | 程咬銅     | male   |  18 | 2015-04-11 | operation                               | NULL         |   18000.00 |    403 |         3 |
| 18 | 程咬鐵     | female |  18 | 2014-05-12 | operation                               | NULL         |   17000.00 |    403 |         3 |
+----+------------+--------+-----+------------+-----------------------------------------+--------------+------------+--------+-----------+
18 rows in set (0.00 sec)

mysql> select name,salary from employee where salary >=20000 and salary <= 30000;
+-----------+----------+
| name      | salary   |
+-----------+----------+
| jinxin    | 30000.00 |
| 程咬金    | 20000.00 |
+-----------+----------+
2 rows in set (0.00 sec)

mysql> select name,salary from employee where salary between 20000 and 30000;
+-----------+----------+
| name      | salary   |
+-----------+----------+
| jinxin    | 30000.00 |
| 程咬金    | 20000.00 |
+-----------+----------+
2 rows in set (0.00 sec)

mysql> select name,salary from employee where salary <20000 or salary > 30000;
+------------+------------+
| name       | salary     |
+------------+------------+
| egon       |    7300.33 |
| alex       | 1000000.31 |
| wupeiqi    |    8300.00 |
| yuanhao    |    3500.00 |
| liwenzhou  |    2100.00 |
| jingliyang |    9000.00 |
| 成龍       |   10000.00 |
| 歪歪       |    3000.13 |
| 丫丫       |    2000.35 |
| 丁丁       |    1000.37 |
| 星星       |    3000.29 |
| 格格       |    4000.33 |
| 張野       |   10000.13 |
| 程咬銀     |   19000.00 |
| 程咬銅     |   18000.00 |
| 程咬鐵     |   17000.00 |
+------------+------------+
16 rows in set (0.00 sec)

mysql> select name,salary from employee where salary not between 20000 and 30000;
+------------+------------+
| name       | salary     |
+------------+------------+
| egon       |    7300.33 |
| alex       | 1000000.31 |
| wupeiqi    |    8300.00 |
| yuanhao    |    3500.00 |
| liwenzhou  |    2100.00 |
| jingliyang |    9000.00 |
| 成龍       |   10000.00 |
| 歪歪       |    3000.13 |
| 丫丫       |    2000.35 |
| 丁丁       |    1000.37 |
| 星星       |    3000.29 |
| 格格       |    4000.33 |
| 張野       |   10000.13 |
| 程咬銀     |   19000.00 |
| 程咬銅     |   18000.00 |
| 程咬鐵     |   17000.00 |
+------------+------------+
16 rows in set (0.00 sec)

mysql> select name,age from employee where age = 73 or age =81 or age =28;
+-----------+-----+
| name      | age |
+-----------+-----+
| wupeiqi   |  81 |
| yuanhao   |  73 |
| liwenzhou |  28 |
| 格格      |  28 |
| 張野      |  28 |
+-----------+-----+
5 rows in set (0.00 sec)

mysql> select * from employee where age in (73,81,28);
+----+-----------+--------+-----+------------+-----------+--------------+----------+--------+-----------+
| id | name      | sex    | age | hire_date  | post      | post_comment | salary   | office | depart_id |
+----+-----------+--------+-----+------------+-----------+--------------+----------+--------+-----------+
|  3 | wupeiqi   | male   |  81 | 2013-03-05 | teacher   | NULL         |  8300.00 |    401 |         1 |
|  4 | yuanhao   | male   |  73 | 2014-07-01 | teacher   | NULL         |  3500.00 |    401 |         1 |
|  5 | liwenzhou | male   |  28 | 2012-11-01 | teacher   | NULL         |  2100.00 |    401 |         1 |
| 13 | 格格      | female |  28 | 2017-01-27 | sale      | NULL         |  4000.33 |    402 |         2 |
| 14 | 張野      | male   |  28 | 2016-03-11 | operation | NULL         | 10000.13 |    403 |         3 |
+----+-----------+--------+-----+------------+-----------+--------------+----------+--------+-----------+
5 rows in set (0.00 sec)

mysql> select * from employee where post = '';
Empty set (0.00 sec)

mysql> select * from employee where post_comment is null;
+----+------------+--------+-----+------------+-----------------------------------------+--------------+------------+--------+-----------+
| id | name       | sex    | age | hire_date  | post                                    | post_comment | salary     | office | depart_id |
+----+------------+--------+-----+------------+-----------------------------------------+--------------+------------+--------+-----------+
|  1 | egon       | male   |  18 | 2017-03-01 | 老男孩駐沙河辦事處外交大使              | NULL         |    7300.33 |    401 |         1 |
|  2 | alex       | male   |  78 | 2015-03-02 | teacher                                 | NULL         | 1000000.31 |    401 |         1 |
|  3 | wupeiqi    | male   |  81 | 2013-03-05 | teacher                                 | NULL         |    8300.00 |    401 |         1 |
|  4 | yuanhao    | male   |  73 | 2014-07-01 | teacher                                 | NULL         |    3500.00 |    401 |         1 |
|  5 | liwenzhou  | male   |  28 | 2012-11-01 | teacher                                 | NULL         |    2100.00 |    401 |         1 |
|  6 | jingliyang | female |  18 | 2011-02-11 | teacher                                 | NULL         |    9000.00 |    401 |         1 |
|  7 | jinxin     | male   |  18 | 1900-03-01 | teacher                                 | NULL         |   30000.00 |    401 |         1 |
|  8 | 成龍       | male   |  48 | 2010-11-11 | teacher                                 | NULL         |   10000.00 |    401 |         1 |
|  9 | 歪歪       | female |  48 | 2015-03-11 | sale                                    | NULL         |    3000.13 |    402 |         2 |
| 10 | 丫丫       | female |  38 | 2010-11-01 | sale                                    | NULL         |    2000.35 |    402 |         2 |
| 11 | 丁丁       | female |  18 | 2011-03-12 | sale                                    | NULL         |    1000.37 |    402 |         2 |
| 12 | 星星       | female |  18 | 2016-05-13 | sale                                    | NULL         |    3000.29 |    402 |         2 |
| 13 | 格格       | female |  28 | 2017-01-27 | sale                                    | NULL         |    4000.33 |    402 |         2 |
| 14 | 張野       | male   |  28 | 2016-03-11 | operation                               | NULL         |   10000.13 |    403 |         3 |
| 15 | 程咬金     | male   |  18 | 1997-03-12 | operation                               | NULL         |   20000.00 |    403 |         3 |
| 16 | 程咬銀     | female |  18 | 2013-03-11 | operation                               | NULL         |   19000.00 |    403 |         3 |
| 17 | 程咬銅     | male   |  18 | 2015-04-11 | operation                               | NULL         |   18000.00 |    403 |         3 |
| 18 | 程咬鐵     | female |  18 | 2014-05-12 | operation                               | NULL         |   17000.00 |    403 |         3 |
+----+------------+--------+-----+------------+-----------------------------------------+--------------+------------+--------+-----------+
18 rows in set (0.00 sec)

mysql> select * from employee where post_comment is not null;
Empty set (0.00 sec)

mysql> select * from employee where name like 'jin%';
+----+------------+--------+-----+------------+---------+--------------+----------+--------+-----------+
| id | name       | sex    | age | hire_date  | post    | post_comment | salary   | office | depart_id |
+----+------------+--------+-----+------------+---------+--------------+----------+--------+-----------+
|  6 | jingliyang | female |  18 | 2011-02-11 | teacher | NULL         |  9000.00 |    401 |         1 |
|  7 | jinxin     | male   |  18 | 1900-03-01 | teacher | NULL         | 30000.00 |    401 |         1 |
+----+------------+--------+-----+------------+---------+--------------+----------+--------+-----------+
2 rows in set (0.00 sec)

mysql> select * from employee where name like 'jin_';
Empty set (0.00 sec)

mysql> select * from employee where name like 'jin___';
+----+--------+------+-----+------------+---------+--------------+----------+--------+-----------+
| id | name   | sex  | age | hire_date  | post    | post_comment | salary   | office | depart_id |
+----+--------+------+-----+------------+---------+--------------+----------+--------+-----------+
|  7 | jinxin | male |  18 | 1900-03-01 | teacher | NULL         | 30000.00 |    401 |         1 |
+----+--------+------+-----+------------+---------+--------------+----------+--------+-----------+
1 row in set (0.00 sec)

mysql>

27-group by分組

一、什麼是分組,咱們爲何要分組?

1)分組發生在where條件以後;

2)將全部記錄按照某個相同的字段進行歸類;

3)小竅門:在「每」這個字後面的字段,就是咱們分組的依據;

4)能夠按照任意字段分組,可是分組完畢後,好比group by post,只能看到post字段,若是查看組內信息,須要藉助於聚合函數;

二、ONLY_FULL_GROUP_BY

查看MySQL5.7默認的sql_mode;

SELECT @@global.sql_mode;

SET GLOBAL sql_mode = 'ONLY_FULL_GROUP_BY';

三、GROUP BY

  • 單獨使用GROUP BY 關鍵字分組;
  • GROUP BY 關鍵字和GROUP_CONCAT()函數一塊兒使用;
  • GROUP BY 與聚合函數一塊兒使用MAX MIN COUNT SUM AVG;

四、聚合函數;

 

    SELECT COUNT(*) FROM employee;
    SELECT COUNT(*) FROM employee WHERE depart_id=1;
    SELECT MAX(salary) FROM employee;
    SELECT MIN(salary) FROM employee;
    SELECT AVG(salary) FROM employee;
    SELECT SUM(salary) FROM employee;
    SELECT SUM(salary) FROM employee WHERE depart_id=3;

 

五、操做日誌:

Enter password: ************
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 39
Server version: 5.7.20-log MySQL Community Server (GPL)

Copyright (c) 2000, 2017, 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> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| engines            |
| luffy_practise     |
| luffycity          |
| mysql              |
| performance_schema |
| sakila             |
| sys                |
| world              |
+--------------------+
9 rows in set (0.00 sec)

mysql> use luffy_practise;
Database changed
mysql> show tables;
+--------------------------+
| Tables_in_luffy_practise |
+--------------------------+
| employee                 |
+--------------------------+
1 row in set (0.00 sec)

mysql> use employee;
ERROR 1049 (42000): Unknown database 'employee'
mysql> desc employee;
+--------------+-----------------------+------+-----+---------+----------------+
| Field        | Type                  | Null | Key | Default | Extra          |
+--------------+-----------------------+------+-----+---------+----------------+
| id           | int(11)               | NO   | PRI | NULL    | auto_increment |
| name         | varchar(20)           | NO   |     | NULL    |                |
| sex          | enum('male','female') | NO   |     | male    |                |
| age          | int(3) unsigned       | NO   |     | 28      |                |
| hire_date    | date                  | NO   |     | NULL    |                |
| post         | varchar(50)           | YES  |     | NULL    |                |
| post_comment | varchar(100)          | YES  |     | NULL    |                |
| salary       | double(15,2)          | YES  |     | NULL    |                |
| office       | int(11)               | YES  |     | NULL    |                |
| depart_id    | int(11)               | YES  |     | NULL    |                |
+--------------+-----------------------+------+-----+---------+----------------+
10 rows in set (0.01 sec)

mysql> select * from employee group by post;
+----+--------+--------+-----+------------+-----------------------------------------+--------------+------------+--------+-----------+
| id | name   | sex    | age | hire_date  | post                                    | post_comment | salary     | office | depart_id |
+----+--------+--------+-----+------------+-----------------------------------------+--------------+------------+--------+-----------+
| 14 | 張野   | male   |  28 | 2016-03-11 | operation                               | NULL         |   10000.13 |    403 |         3 |
|  9 | 歪歪   | female |  48 | 2015-03-11 | sale                                    | NULL         |    3000.13 |    402 |         2 |
|  2 | alex   | male   |  78 | 2015-03-02 | teacher                                 | NULL         | 1000000.31 |    401 |         1 |
|  1 | egon   | male   |  18 | 2017-03-01 | 老男孩駐沙河辦事處外交大使              | NULL         |    7300.33 |    401 |         1 |
+----+--------+--------+-----+------------+-----------------------------------------+--------------+------------+--------+-----------+
4 rows in set (0.00 sec)

mysql> set global sql_mode = 'ONLY_FULL_GROUP_BY';
Query OK, 0 rows affected, 1 warning (0.00 sec)

mysql> select post from employee group by post;
+-----------------------------------------+
| post                                    |
+-----------------------------------------+
| operation                               |
| sale                                    |
| teacher                                 |
| 老男孩駐沙河辦事處外交大使              |
+-----------------------------------------+
4 rows in set (0.00 sec)

mysql> select post,count(id) from employee group by post;
+-----------------------------------------+-----------+
| post                                    | count(id) |
+-----------------------------------------+-----------+
| operation                               |         5 |
| sale                                    |         5 |
| teacher                                 |         7 |
| 老男孩駐沙河辦事處外交大使              |         1 |
+-----------------------------------------+-----------+
4 rows in set (0.00 sec)

mysql> select post,count(id) as employee_id from employee group by post;
+-----------------------------------------+-------------+
| post                                    | employee_id |
+-----------------------------------------+-------------+
| operation                               |           5 |
| sale                                    |           5 |
| teacher                                 |           7 |
| 老男孩駐沙河辦事處外交大使              |           1 |
+-----------------------------------------+-------------+
4 rows in set (0.00 sec)

mysql> select post,max(salary) as employee_id from employee group by post;
+-----------------------------------------+-------------+
| post                                    | employee_id |
+-----------------------------------------+-------------+
| operation                               |    20000.00 |
| sale                                    |     4000.33 |
| teacher                                 |  1000000.31 |
| 老男孩駐沙河辦事處外交大使              |     7300.33 |
+-----------------------------------------+-------------+
4 rows in set (0.00 sec)

mysql> select post,min(salary) as employee_id from employee group by post;
+-----------------------------------------+-------------+
| post                                    | employee_id |
+-----------------------------------------+-------------+
| operation                               |    10000.13 |
| sale                                    |     1000.37 |
| teacher                                 |     2100.00 |
| 老男孩駐沙河辦事處外交大使              |     7300.33 |
+-----------------------------------------+-------------+
4 rows in set (0.00 sec)

mysql> select post,avg(salary) as employee_id from employee group by post;
+-----------------------------------------+---------------+
| post                                    | employee_id   |
+-----------------------------------------+---------------+
| operation                               |  16800.026000 |
| sale                                    |   2600.294000 |
| teacher                                 | 151842.901429 |
| 老男孩駐沙河辦事處外交大使              |   7300.330000 |
+-----------------------------------------+---------------+
4 rows in set (0.00 sec)

mysql> select post,count(salary) as employee_id from employee group by post;
+-----------------------------------------+-------------+
| post                                    | employee_id |
+-----------------------------------------+-------------+
| operation                               |           5 |
| sale                                    |           5 |
| teacher                                 |           7 |
| 老男孩駐沙河辦事處外交大使              |           1 |
+-----------------------------------------+-------------+
4 rows in set (0.00 sec)

mysql> select post,sum(salary) as employee_id from employee group by post;
+-----------------------------------------+-------------+
| post                                    | employee_id |
+-----------------------------------------+-------------+
| operation                               |    84000.13 |
| sale                                    |    13001.47 |
| teacher                                 |  1062900.31 |
| 老男孩駐沙河辦事處外交大使              |     7300.33 |
+-----------------------------------------+-------------+
4 rows in set (0.00 sec)

mysql> select max(salary) from employee;
+-------------+
| max(salary) |
+-------------+
|  1000000.31 |
+-------------+
1 row in set (0.00 sec)

mysql> select name,max(salary) from employee;
+------+-------------+
| name | max(salary) |
+------+-------------+
| egon |  1000000.31 |
+------+-------------+
1 row in set (0.00 sec)

mysql> select name,salary from employee;
+------------+------------+
| name       | salary     |
+------------+------------+
| egon       |    7300.33 |
| alex       | 1000000.31 |
| wupeiqi    |    8300.00 |
| yuanhao    |    3500.00 |
| liwenzhou  |    2100.00 |
| jingliyang |    9000.00 |
| jinxin     |   30000.00 |
| 成龍       |   10000.00 |
| 歪歪       |    3000.13 |
| 丫丫       |    2000.35 |
| 丁丁       |    1000.37 |
| 星星       |    3000.29 |
| 格格       |    4000.33 |
| 張野       |   10000.13 |
| 程咬金     |   20000.00 |
| 程咬銀     |   19000.00 |
| 程咬銅     |   18000.00 |
| 程咬鐵     |   17000.00 |
+------------+------------+
18 rows in set (0.00 sec)

mysql> select name,max(salary) from employee;
+------+-------------+
| name | max(salary) |
+------+-------------+
| egon |  1000000.31 |
+------+-------------+
1 row in set (0.00 sec)

mysql> select post,group_concat(name) from employee group by post;
+-----------------------------------------+---------------------------------------------------------+
| post                                    | group_concat(name)                                      |
+-----------------------------------------+---------------------------------------------------------+
| operation                               | 張野,程咬金,程咬銀,程咬銅,程咬鐵                        |
| sale                                    | 歪歪,丫丫,丁丁,星星,格格                                |
| teacher                                 | alex,wupeiqi,yuanhao,liwenzhou,jingliyang,jinxin,成龍   |
| 老男孩駐沙河辦事處外交大使              | egon                                                    |
+-----------------------------------------+---------------------------------------------------------+
4 rows in set (0.00 sec)

mysql> select post,group_concat(name) from employee group by post;
+-----------------------------------------+---------------------------------------------------------+
| post                                    | group_concat(name)                                      |
+-----------------------------------------+---------------------------------------------------------+
| operation                               | 張野,程咬金,程咬銀,程咬銅,程咬鐵                        |
| sale                                    | 歪歪,丫丫,丁丁,星星,格格                                |
| teacher                                 | alex,wupeiqi,yuanhao,liwenzhou,jingliyang,jinxin,成龍   |
| 老男孩駐沙河辦事處外交大使              | egon                                                    |
+-----------------------------------------+---------------------------------------------------------+
4 rows in set (0.00 sec)

mysql> select post,count(id) from employee where age > 50 group by post;
+---------+-----------+
| post    | count(id) |
+---------+-----------+
| teacher |         3 |
+---------+-----------+
1 row in set (0.00 sec)

mysql> select sex,count(id) from employee group by sex;
+--------+-----------+
| sex    | count(id) |
+--------+-----------+
| male   |        10 |
| female |         8 |
+--------+-----------+
2 rows in set (0.00 sec)

mysql> select sex,avg(salary) from employee group by sex;
+--------+---------------+
| sex    | avg(salary)   |
+--------+---------------+
| male   | 110920.077000 |
| female |   7250.183750 |
+--------+---------------+
2 rows in set (0.00 sec)

mysql>

28-having過濾

一、查詢順序;

SELECT DISTINCT 字段1,字段2,字段n... from 庫名.表名 
    WHERE 過濾條件
    GROUP BY 分組過濾條件
    HAVING 過濾
    ORDER BY 排序字段
    LIMIT n(限制的條數);
HAVING與WHERE不一樣之處;
#1. Where 發生在分組group by以前,於是Where中能夠有任意字段,可是絕對不能使用聚合函數;

#2. Having發生在分組group by以後,於是Having中可使用分組的字段,沒法直接取到其餘字段,可使用聚合函數;
 

二、操做日誌;

Enter password: ************
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 40
Server version: 5.7.20-log MySQL Community Server (GPL)

Copyright (c) 2000, 2017, 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> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| engines            |
| luffy_practise     |
| luffycity          |
| mysql              |
| performance_schema |
| sakila             |
| sys                |
| world              |
+--------------------+
9 rows in set (0.00 sec)

mysql> use luffy_practise;
Database changed
mysql> show tables;
+--------------------------+
| Tables_in_luffy_practise |
+--------------------------+
| employee                 |
+--------------------------+
1 row in set (0.00 sec)

mysql> desc employee;
+--------------+-----------------------+------+-----+---------+----------------+
| Field        | Type                  | Null | Key | Default | Extra          |
+--------------+-----------------------+------+-----+---------+----------------+
| id           | int(11)               | NO   | PRI | NULL    | auto_increment |
| name         | varchar(20)           | NO   |     | NULL    |                |
| sex          | enum('male','female') | NO   |     | male    |                |
| age          | int(3) unsigned       | NO   |     | 28      |                |
| hire_date    | date                  | NO   |     | NULL    |                |
| post         | varchar(50)           | YES  |     | NULL    |                |
| post_comment | varchar(100)          | YES  |     | NULL    |                |
| salary       | double(15,2)          | YES  |     | NULL    |                |
| office       | int(11)               | YES  |     | NULL    |                |
| depart_id    | int(11)               | YES  |     | NULL    |                |
+--------------+-----------------------+------+-----+---------+----------------+
10 rows in set (0.00 sec)

mysql> select post,group_concat(name),count(id) from employee grop by post;
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 'by post' at line 1
mysql> select post,group_concat(name),count(id) from employee group by post;
+-----------------------------------------+---------------------------------------------------------+-----------+
| post                                    | group_concat(name)                                      | count(id) |
+-----------------------------------------+---------------------------------------------------------+-----------+
| operation                               | 張野,程咬金,程咬銀,程咬銅,程咬鐵                        |         5 |
| sale                                    | 歪歪,丫丫,丁丁,星星,格格                                |         5 |
| teacher                                 | alex,wupeiqi,yuanhao,liwenzhou,jingliyang,jinxin,成龍   |         7 |
| 老男孩駐沙河辦事處外交大使              | egon                                                    |         1 |
+-----------------------------------------+---------------------------------------------------------+-----------+
4 rows in set (0.00 sec)

mysql> select post,group_concat(name),count(id) from employee group by post having count(id);
+-----------------------------------------+---------------------------------------------------------+-----------+
| post                                    | group_concat(name)                                      | count(id) |
+-----------------------------------------+---------------------------------------------------------+-----------+
| operation                               | 張野,程咬金,程咬銀,程咬銅,程咬鐵                        |         5 |
| sale                                    | 歪歪,丫丫,丁丁,星星,格格                                |         5 |
| teacher                                 | alex,wupeiqi,yuanhao,liwenzhou,jingliyang,jinxin,成龍   |         7 |
| 老男孩駐沙河辦事處外交大使              | egon                                                    |         1 |
+-----------------------------------------+---------------------------------------------------------+-----------+
4 rows in set (0.00 sec)

mysql> select post,avg(salary) from employee group by post having avg(salary) > 10000;
+-----------+---------------+
| post      | avg(salary)   |
+-----------+---------------+
| operation |  16800.026000 |
| teacher   | 151842.901429 |
+-----------+---------------+
2 rows in set (0.00 sec)

mysql> select post,avg(salary) from employee group by post having avg(salary) > 10000 and avg(salary)< 20000;
+-----------+--------------+
| post      | avg(salary)  |
+-----------+--------------+
| operation | 16800.026000 |
+-----------+--------------+
1 row in set (0.00 sec)

mysql> select post,avg(salary) from employee group by post having avg(salary) > 10000 and avg(salary)< 200000;
+-----------+---------------+
| post      | avg(salary)   |
+-----------+---------------+
| operation |  16800.026000 |
| teacher   | 151842.901429 |
+-----------+---------------+
2 rows in set (0.00 sec)

mysql>

29-order by排序

一、不指定排序規則,默認按照id從小到大排序;

語法正確,但有可能從執行順序的角度來看,不符合邏輯;

二、操做日誌;

mysql> select max(salary) from employee where max(salary);
ERROR 1111 (HY000): Invalid use of group function
mysql> select * from employee where salary >1000 group by post having count(id ) > 5;
ERROR 1055 (42000): Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'luffy_practise.employee.id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by
mysql> set global sql_mode = only_full_group_by;
Query OK, 0 rows affected (0.00 sec)

mysql> select * from employee where salary >1000 group by post having count(id ) > 5;
ERROR 1055 (42000): Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'luffy_practise.employee.id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by
mysql> set global sql_mode = only_full_group_by;
Query OK, 0 rows affected (0.00 sec)

mysql> select post,count(id) from employee where salary >1000 group by post having count(id ) > 5;
+---------+-----------+
| post    | count(id) |
+---------+-----------+
| teacher |         7 |
+---------+-----------+
1 row in set (0.00 sec)

mysql> select distinct post,count(id) ad emp_count from employee where salary >1000 group by post having count(id) >1 order by emp_count desc;
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 'emp_count from employee where salary >1000 group by post having count(id) >1 ord' at line 1
mysql> select distinct post,count(id) as emp_count from employee where salary >1000 group by post having count(id) >1 order by emp_count desc;
+-----------+-----------+
| post      | emp_count |
+-----------+-----------+
| teacher   |         7 |
| sale      |         5 |
| operation |         5 |
+-----------+-----------+
3 rows in set (0.00 sec)

mysql> select distinct post,count(id) as emp_count from employee where salary >1000 group by post having count(id) >1 order by emp_count asc;
+-----------+-----------+
| post      | emp_count |
+-----------+-----------+
| sale      |         5 |
| operation |         5 |
| teacher   |         7 |
+-----------+-----------+
3 rows in set (0.00 sec)

30-limit限制條數

一、limit關鍵字限制條數(limit 5,4);

二、操做日誌;

mysql> select * from employee limit 3;
+----+---------+------+-----+------------+-----------------------------------------+--------------+------------+--------+-----------+
| id | name    | sex  | age | hire_date  | post                                    | post_comment | salary     | office | depart_id |
+----+---------+------+-----+------------+-----------------------------------------+--------------+------------+--------+-----------+
|  1 | egon    | male |  18 | 2017-03-01 | 老男孩駐沙河辦事處外交大使              | NULL         |    7300.33 |    401 |         1 |
|  2 | alex    | male |  78 | 2015-03-02 | teacher                                 | NULL         | 1000000.31 |    401 |         1 |
|  3 | wupeiqi | male |  81 | 2013-03-05 | teacher                                 | NULL         |    8300.00 |    401 |         1 |
+----+---------+------+-----+------------+-----------------------------------------+--------------+------------+--------+-----------+
3 rows in set (0.00 sec)

mysql> select * from employee order by salary desc limit 1;
+----+------+------+-----+------------+---------+--------------+------------+--------+-----------+
| id | name | sex  | age | hire_date  | post    | post_comment | salary     | office | depart_id |
+----+------+------+-----+------------+---------+--------------+------------+--------+-----------+
|  2 | alex | male |  78 | 2015-03-02 | teacher | NULL         | 1000000.31 |    401 |         1 |
+----+------+------+-----+------------+---------+--------------+------------+--------+-----------+
1 row in set (0.00 sec)

mysql> select * from employee limit 0,5;
+----+-----------+------+-----+------------+-----------------------------------------+--------------+------------+--------+-----------+
| id | name      | sex  | age | hire_date  | post                                    | post_comment | salary     | office | depart_id |
+----+-----------+------+-----+------------+-----------------------------------------+--------------+------------+--------+-----------+
|  1 | egon      | male |  18 | 2017-03-01 | 老男孩駐沙河辦事處外交大使              | NULL         |    7300.33 |    401 |         1 |
|  2 | alex      | male |  78 | 2015-03-02 | teacher                                 | NULL         | 1000000.31 |    401 |         1 |
|  3 | wupeiqi   | male |  81 | 2013-03-05 | teacher                                 | NULL         |    8300.00 |    401 |         1 |
|  4 | yuanhao   | male |  73 | 2014-07-01 | teacher                                 | NULL         |    3500.00 |    401 |         1 |
|  5 | liwenzhou | male |  28 | 2012-11-01 | teacher                                 | NULL         |    2100.00 |    401 |         1 |
+----+-----------+------+-----+------------+-----------------------------------------+--------------+------------+--------+-----------+
5 rows in set (0.00 sec)

mysql> select * from employee limit 5,10;
+----+------------+--------+-----+------------+-----------+--------------+----------+--------+-----------+
| id | name       | sex    | age | hire_date  | post      | post_comment | salary   | office | depart_id |
+----+------------+--------+-----+------------+-----------+--------------+----------+--------+-----------+
|  6 | jingliyang | female |  18 | 2011-02-11 | teacher   | NULL         |  9000.00 |    401 |         1 |
|  7 | jinxin     | male   |  18 | 1900-03-01 | teacher   | NULL         | 30000.00 |    401 |         1 |
|  8 | 成龍       | male   |  48 | 2010-11-11 | teacher   | NULL         | 10000.00 |    401 |         1 |
|  9 | 歪歪       | female |  48 | 2015-03-11 | sale      | NULL         |  3000.13 |    402 |         2 |
| 10 | 丫丫       | female |  38 | 2010-11-01 | sale      | NULL         |  2000.35 |    402 |         2 |
| 11 | 丁丁       | female |  18 | 2011-03-12 | sale      | NULL         |  1000.37 |    402 |         2 |
| 12 | 星星       | female |  18 | 2016-05-13 | sale      | NULL         |  3000.29 |    402 |         2 |
| 13 | 格格       | female |  28 | 2017-01-27 | sale      | NULL         |  4000.33 |    402 |         2 |
| 14 | 張野       | male   |  28 | 2016-03-11 | operation | NULL         | 10000.13 |    403 |         3 |
| 15 | 程咬金     | male   |  18 | 1997-03-12 | operation | NULL         | 20000.00 |    403 |         3 |
+----+------------+--------+-----+------------+-----------+--------------+----------+--------+-----------+
10 rows in set (0.00 sec)

mysql> select * from employee limit 10,20;
+----+-----------+--------+-----+------------+-----------+--------------+----------+--------+-----------+
| id | name      | sex    | age | hire_date  | post      | post_comment | salary   | office | depart_id |
+----+-----------+--------+-----+------------+-----------+--------------+----------+--------+-----------+
| 11 | 丁丁      | female |  18 | 2011-03-12 | sale      | NULL         |  1000.37 |    402 |         2 |
| 12 | 星星      | female |  18 | 2016-05-13 | sale      | NULL         |  3000.29 |    402 |         2 |
| 13 | 格格      | female |  28 | 2017-01-27 | sale      | NULL         |  4000.33 |    402 |         2 |
| 14 | 張野      | male   |  28 | 2016-03-11 | operation | NULL         | 10000.13 |    403 |         3 |
| 15 | 程咬金    | male   |  18 | 1997-03-12 | operation | NULL         | 20000.00 |    403 |         3 |
| 16 | 程咬銀    | female |  18 | 2013-03-11 | operation | NULL         | 19000.00 |    403 |         3 |
| 17 | 程咬銅    | male   |  18 | 2015-04-11 | operation | NULL         | 18000.00 |    403 |         3 |
| 18 | 程咬鐵    | female |  18 | 2014-05-12 | operation | NULL         | 17000.00 |    403 |         3 |
+----+-----------+--------+-----+------------+-----------+--------------+----------+--------+-----------+
8 rows in set (0.00 sec)

mysql> select * from employee limit 15,5;
+----+-----------+--------+-----+------------+-----------+--------------+----------+--------+-----------+
| id | name      | sex    | age | hire_date  | post      | post_comment | salary   | office | depart_id |
+----+-----------+--------+-----+------------+-----------+--------------+----------+--------+-----------+
| 16 | 程咬銀    | female |  18 | 2013-03-11 | operation | NULL         | 19000.00 |    403 |         3 |
| 17 | 程咬銅    | male   |  18 | 2015-04-11 | operation | NULL         | 18000.00 |    403 |         3 |
| 18 | 程咬鐵    | female |  18 | 2014-05-12 | operation | NULL         | 17000.00 |    403 |         3 |
+----+-----------+--------+-----+------------+-----------+--------------+----------+--------+-----------+
3 rows in set (0.00 sec)

mysql>

31-單表查詢的語法順序與執行順序總結

一、單表查詢總結;

1)語法順序;

2)執行順序

def from(db,table):
    f = open(r'%s\%s'%(db,table))
    return f

def where(condition,f):
    for line in f:
        if condition:
            yield line

def group(lines):
    pass

def having(group_res):
    pass

def distinct(having_res):
    pass

def order(distinct_res):
    pass

def limit(order_res):
    pass

def select():
    f = from('db1','t1')
    lines = where('id>3',f)
    group_res = group(lines)
    having_res = having(group_res)
    distinct(having_res)
    order_res = order(distinct_res)
    res = limit(order_res)
    print(res)
    return res
 使用以上該方式,講解select的語法順序及執行順序;

32-正則查詢

一、正則表達式查詢;

  • regexp 
SELECT * FROM employee WHERE NAME LIKE 'jin%';#like關鍵字模糊匹配;
SELECT * FROM employee WHERE NAME regexp '^jin';#引入正則;
SELECT * FROM employee WHERE NAME regexp '^jin.*(g|n)%';#引入正則;

33-連表操做

一、連表的分類;

  • 內鏈接 
  • 左鏈接
  • 右鏈接
  • 全外鏈接
#內鏈接:只取兩張表的共同部分
select * from employee inner join department on employee.dep_id = department.id 
#左鏈接:在內鏈接的基礎上,保留左表的記錄;
select * from employee left join department on employee.dep_id = deparment.id;
#右鏈接:在內鏈接的基礎上,保留右表的記錄;
select * from employee right join department on employee.dep_id = department.id;
#全外鏈接:在內鏈接的基礎上,保留左右兩張表沒有對應關係的記錄;
select * from employee full join(其餘數據庫庫可能支持,MySQL不支持)


select * from employee left join department on employee.dep_id = deparment.id union select * from employee right join department on employee.dep_id = department.id;

 

Enter password: ************
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 41
Server version: 5.7.20-log MySQL Community Server (GPL)

Copyright (c) 2000, 2017, 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> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| engines            |
| luffy_practise     |
| luffycity          |
| mysql              |
| performance_schema |
| sakila             |
| sys                |
| world              |
+--------------------+
9 rows in set (0.00 sec)

mysql> use luffy_practise;
Database changed
mysql> show tables;
+--------------------------+
| Tables_in_luffy_practise |
+--------------------------+
| employee                 |
+--------------------------+
1 row in set (0.00 sec)

mysql> create table department(
    -> id int
    -> ^C
mysql> create table department(
    -> id int,
    -> name varchar(20)
    -> );
Query OK, 0 rows affected (0.02 sec)

mysql> alter table employee rename to employee_history;
Query OK, 0 rows affected (0.01 sec)

mysql> create table employee(
    -> id int primary key auto_increment,
    -> name varchar(20),
    -> sex enum('male','female')not null default 'male',
    -> age int,
    -> dep_id int
    -> );
Query OK, 0 rows affected (0.02 sec)

mysql> insert into department values
    -> (200,'技術'),
    -> (201,'人力資源'),
    -> (202,'銷售'),
    -> (203,'運營');
Query OK, 4 rows affected (0.01 sec)
Records: 4  Duplicates: 0  Warnings: 0

mysql> insert into employee(name,sex,age,dep_id) values
    -> ('egon','male',18,200),
    -> ('alex','female',48,201),
    -> ('wupeiqi','male',38,201),
    -> ('yuanhao','female',28,202),
    -> ('liwenzhou','male',18,200),
    -> ('jingliyang','female',18,204)
    -> ;
Query OK, 6 rows affected (0.00 sec)
Records: 6  Duplicates: 0  Warnings: 0

mysql> desc department;
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| id    | int(11)     | YES  |     | NULL    |       |
| name  | varchar(20) | YES  |     | NULL    |       |
+-------+-------------+------+-----+---------+-------+
2 rows in set (0.00 sec)

mysql> desc employee;
+--------+-----------------------+------+-----+---------+----------------+
| Field  | Type                  | Null | Key | Default | Extra          |
+--------+-----------------------+------+-----+---------+----------------+
| id     | int(11)               | NO   | PRI | NULL    | auto_increment |
| name   | varchar(20)           | YES  |     | NULL    |                |
| sex    | enum('male','female') | NO   |     | male    |                |
| age    | int(11)               | YES  |     | NULL    |                |
| dep_id | int(11)               | YES  |     | NULL    |                |
+--------+-----------------------+------+-----+---------+----------------+
5 rows in set (0.00 sec)

mysql> select * from department;
+------+--------------+
| id   | name         |
+------+--------------+
|  200 | 技術         |
|  201 | 人力資源     |
|  202 | 銷售         |
|  203 | 運營         |
+------+--------------+
4 rows in set (0.00 sec)

mysql> select * from employee;
+----+------------+--------+------+--------+
| id | name       | sex    | age  | dep_id |
+----+------------+--------+------+--------+
|  1 | egon       | male   |   18 |    200 |
|  2 | alex       | female |   48 |    201 |
|  3 | wupeiqi    | male   |   38 |    201 |
|  4 | yuanhao    | female |   28 |    202 |
|  5 | liwenzhou  | male   |   18 |    200 |
|  6 | jingliyang | female |   18 |    204 |
+----+------------+--------+------+--------+
6 rows in set (0.00 sec)

mysql> select * from employee,department;
+----+------------+--------+------+--------+------+--------------+
| id | name       | sex    | age  | dep_id | id   | name         |
+----+------------+--------+------+--------+------+--------------+
|  1 | egon       | male   |   18 |    200 |  200 | 技術         |
|  1 | egon       | male   |   18 |    200 |  201 | 人力資源     |
|  1 | egon       | male   |   18 |    200 |  202 | 銷售         |
|  1 | egon       | male   |   18 |    200 |  203 | 運營         |
|  2 | alex       | female |   48 |    201 |  200 | 技術         |
|  2 | alex       | female |   48 |    201 |  201 | 人力資源     |
|  2 | alex       | female |   48 |    201 |  202 | 銷售         |
|  2 | alex       | female |   48 |    201 |  203 | 運營         |
|  3 | wupeiqi    | male   |   38 |    201 |  200 | 技術         |
|  3 | wupeiqi    | male   |   38 |    201 |  201 | 人力資源     |
|  3 | wupeiqi    | male   |   38 |    201 |  202 | 銷售         |
|  3 | wupeiqi    | male   |   38 |    201 |  203 | 運營         |
|  4 | yuanhao    | female |   28 |    202 |  200 | 技術         |
|  4 | yuanhao    | female |   28 |    202 |  201 | 人力資源     |
|  4 | yuanhao    | female |   28 |    202 |  202 | 銷售         |
|  4 | yuanhao    | female |   28 |    202 |  203 | 運營         |
|  5 | liwenzhou  | male   |   18 |    200 |  200 | 技術         |
|  5 | liwenzhou  | male   |   18 |    200 |  201 | 人力資源     |
|  5 | liwenzhou  | male   |   18 |    200 |  202 | 銷售         |
|  5 | liwenzhou  | male   |   18 |    200 |  203 | 運營         |
|  6 | jingliyang | female |   18 |    204 |  200 | 技術         |
|  6 | jingliyang | female |   18 |    204 |  201 | 人力資源     |
|  6 | jingliyang | female |   18 |    204 |  202 | 銷售         |
|  6 | jingliyang | female |   18 |    204 |  203 | 運營         |
+----+------------+--------+------+--------+------+--------------+
24 rows in set (0.00 sec)

mysql> select employee.id,employee.name,employee.age,employee.sex,department.name from employee inner join department on employee.dep_id = department.id;
+----+-----------+------+--------+--------------+
| id | name      | age  | sex    | name         |
+----+-----------+------+--------+--------------+
|  1 | egon      |   18 | male   | 技術         |
|  2 | alex      |   48 | female | 人力資源     |
|  3 | wupeiqi   |   38 | male   | 人力資源     |
|  4 | yuanhao   |   28 | female | 銷售         |
|  5 | liwenzhou |   18 | male   | 技術         |
+----+-----------+------+--------+--------------+
5 rows in set (0.00 sec)

mysql> select employee.id,employee.name,department.name as depart_name from employee left join department on employee.dep_id = department.id;
+----+------------+--------------+
| id | name       | depart_name  |
+----+------------+--------------+
|  1 | egon       | 技術         |
|  5 | liwenzhou  | 技術         |
|  2 | alex       | 人力資源     |
|  3 | wupeiqi    | 人力資源     |
|  4 | yuanhao    | 銷售         |
|  6 | jingliyang | NULL         |
+----+------------+--------------+
6 rows in set (0.00 sec)

mysql> select employee.id,employee.name,department.name as depart_name from employee right join department on employee.dep_id = department.id;
+------+-----------+--------------+
| id   | name      | depart_name  |
+------+-----------+--------------+
|    1 | egon      | 技術         |
|    2 | alex      | 人力資源     |
|    3 | wupeiqi   | 人力資源     |
|    4 | yuanhao   | 銷售         |
|    5 | liwenzhou | 技術         |
| NULL | NULL      | 運營         |
+------+-----------+--------------+
6 rows in set (0.00 sec)

mysql> select * from employee left join department on employee.dep_id = department.id
    -> union
    -> select * from employee right join department on employee.dep_id = department.id
    -> ;
+------+------------+--------+------+--------+------+--------------+
| id   | name       | sex    | age  | dep_id | id   | name         |
+------+------------+--------+------+--------+------+--------------+
|    1 | egon       | male   |   18 |    200 |  200 | 技術         |
|    5 | liwenzhou  | male   |   18 |    200 |  200 | 技術         |
|    2 | alex       | female |   48 |    201 |  201 | 人力資源     |
|    3 | wupeiqi    | male   |   38 |    201 |  201 | 人力資源     |
|    4 | yuanhao    | female |   28 |    202 |  202 | 銷售         |
|    6 | jingliyang | female |   18 |    204 | NULL | NULL         |
| NULL | NULL       | NULL   | NULL |   NULL |  203 | 運營         |
+------+------------+--------+------+--------+------+--------------+
7 rows in set (0.00 sec)

mysql>

34-select語句關鍵字執行優先級

一、完整的語法;

二、執行順序;

35-子查詢

一、練習1;

select name from department where id in (select dep_id from employee group by dep_id having avg(age) > 25);

二、練習2;

select * from employee where dep_id = (select id from department where name = '技術部');

三、練習3;

select name from department where id not in (select distinct dep_id from employee);

四、練習4;

select * from employee where exists (select id from department where name = '技術部');

五、練習5;

select * from employee as t1 inner join (select post,max(hire_date) as max_hire_date from employee group by post) as t2 on t1.post = t2.post
where t1.hire_date = t2.max_hire_date;

36-多表查詢練習

一、基礎數據準備;

/*
 數據導入:
 Navicat Premium Data Transfer

 Source Server         : localhost
 Source Server Type    : MySQL
 Source Server Version : 50624
 Source Host           : localhost
 Source Database       : sqlexam

 Target Server Type    : MySQL
 Target Server Version : 50624
 File Encoding         : utf-8

 Date: 10/21/2016 06:46:46 AM
*/

SET NAMES utf8;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
--  Table structure for `class`
-- ----------------------------
DROP TABLE IF EXISTS `class`;
CREATE TABLE `class` (
  `cid` int(11) NOT NULL AUTO_INCREMENT,
  `caption` varchar(32) NOT NULL,
  PRIMARY KEY (`cid`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;

-- ----------------------------
--  Records of `class`
-- ----------------------------
BEGIN;
INSERT INTO `class` VALUES ('1', '三年二班'), ('2', '三年三班'), ('3', '一年二班'), ('4', '二年九班');
COMMIT;

-- ----------------------------
--  Table structure for `course`
-- ----------------------------
DROP TABLE IF EXISTS `course`;
CREATE TABLE `course` (
  `cid` int(11) NOT NULL AUTO_INCREMENT,
  `cname` varchar(32) NOT NULL,
  `teacher_id` int(11) NOT NULL,
  PRIMARY KEY (`cid`),
  KEY `fk_course_teacher` (`teacher_id`),
  CONSTRAINT `fk_course_teacher` FOREIGN KEY (`teacher_id`) REFERENCES `teacher` (`tid`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;

-- ----------------------------
--  Records of `course`
-- ----------------------------
BEGIN;
INSERT INTO `course` VALUES ('1', '生物', '1'), ('2', '物理', '2'), ('3', '體育', '3'), ('4', '美術', '2');
COMMIT;

-- ----------------------------
--  Table structure for `score`
-- ----------------------------
DROP TABLE IF EXISTS `score`;
CREATE TABLE `score` (
  `sid` int(11) NOT NULL AUTO_INCREMENT,
  `student_id` int(11) NOT NULL,
  `course_id` int(11) NOT NULL,
  `num` int(11) NOT NULL,
  PRIMARY KEY (`sid`),
  KEY `fk_score_student` (`student_id`),
  KEY `fk_score_course` (`course_id`),
  CONSTRAINT `fk_score_course` FOREIGN KEY (`course_id`) REFERENCES `course` (`cid`),
  CONSTRAINT `fk_score_student` FOREIGN KEY (`student_id`) REFERENCES `student` (`sid`)
) ENGINE=InnoDB AUTO_INCREMENT=53 DEFAULT CHARSET=utf8;

-- ----------------------------
--  Records of `score`
-- ----------------------------
BEGIN;
INSERT INTO `score` VALUES ('1', '1', '1', '10'), ('2', '1', '2', '9'), ('5', '1', '4', '66'), ('6', '2', '1', '8'), ('8', '2', '3', '68'), ('9', '2', '4', '99'), ('10', '3', '1', '77'), ('11', '3', '2', '66'), ('12', '3', '3', '87'), ('13', '3', '4', '99'), ('14', '4', '1', '79'), ('15', '4', '2', '11'), ('16', '4', '3', '67'), ('17', '4', '4', '100'), ('18', '5', '1', '79'), ('19', '5', '2', '11'), ('20', '5', '3', '67'), ('21', '5', '4', '100'), ('22', '6', '1', '9'), ('23', '6', '2', '100'), ('24', '6', '3', '67'), ('25', '6', '4', '100'), ('26', '7', '1', '9'), ('27', '7', '2', '100'), ('28', '7', '3', '67'), ('29', '7', '4', '88'), ('30', '8', '1', '9'), ('31', '8', '2', '100'), ('32', '8', '3', '67'), ('33', '8', '4', '88'), ('34', '9', '1', '91'), ('35', '9', '2', '88'), ('36', '9', '3', '67'), ('37', '9', '4', '22'), ('38', '10', '1', '90'), ('39', '10', '2', '77'), ('40', '10', '3', '43'), ('41', '10', '4', '87'), ('42', '11', '1', '90'), ('43', '11', '2', '77'), ('44', '11', '3', '43'), ('45', '11', '4', '87'), ('46', '12', '1', '90'), ('47', '12', '2', '77'), ('48', '12', '3', '43'), ('49', '12', '4', '87'), ('52', '13', '3', '87');
COMMIT;

-- ----------------------------
--  Table structure for `student`
-- ----------------------------
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student` (
  `sid` int(11) NOT NULL AUTO_INCREMENT,
  `gender` char(1) NOT NULL,
  `class_id` int(11) NOT NULL,
  `sname` varchar(32) NOT NULL,
  PRIMARY KEY (`sid`),
  KEY `fk_class` (`class_id`),
  CONSTRAINT `fk_class` FOREIGN KEY (`class_id`) REFERENCES `class` (`cid`)
) ENGINE=InnoDB AUTO_INCREMENT=17 DEFAULT CHARSET=utf8;

-- ----------------------------
--  Records of `student`
-- ----------------------------
BEGIN;
INSERT INTO `student` VALUES ('1', '', '1', '理解'), ('2', '', '1', '鋼蛋'), ('3', '', '1', '張三'), ('4', '', '1', '張一'), ('5', '', '1', '張二'), ('6', '', '1', '張四'), ('7', '', '2', '鐵錘'), ('8', '', '2', '李三'), ('9', '', '2', '李一'), ('10', '', '2', '李二'), ('11', '', '2', '李四'), ('12', '', '3', '如花'), ('13', '', '3', '劉三'), ('14', '', '3', '劉一'), ('15', '', '3', '劉二'), ('16', '', '3', '劉四');
COMMIT;

-- ----------------------------
--  Table structure for `teacher`
-- ----------------------------
DROP TABLE IF EXISTS `teacher`;
CREATE TABLE `teacher` (
  `tid` int(11) NOT NULL AUTO_INCREMENT,
  `tname` varchar(32) NOT NULL,
  PRIMARY KEY (`tid`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;

-- ----------------------------
--  Records of `teacher`
-- ----------------------------
BEGIN;
INSERT INTO `teacher` VALUES ('1', '張磊老師'), ('2', '李平老師'), ('3', '劉海燕老師'), ('4', '朱雲海老師'), ('5', '李傑老師');
COMMIT;

SET FOREIGN_KEY_CHECKS = 1;

二、查詢練習;

一、查詢全部的課程的名稱以及對應的任課老師姓名

二、查詢學生表中男女生各有多少人

三、查詢物理成績等於100的學生的姓名

四、查詢平均成績大於八十分的同窗的姓名和平均成績

五、查詢全部學生的學號,姓名,選課數,總成績

六、 查詢姓李老師的個數

七、 查詢沒有報李平老師課的學生姓名

八、 查詢物理課程比生物課程高的學生的學號

九、 查詢沒有同時選修物理課程和體育課程的學生姓名

十、查詢掛科超過兩門(包括兩門)的學生姓名和班級
、查詢選修了全部課程的學生姓名

十二、查詢李平老師教的課程的全部成績記錄

1三、查詢所有學生都選修了的課程號和課程名

1四、查詢每門課程被選修的次數

1五、查詢之選修了一門課程的學生姓名和學號

1六、查詢全部學生考出的成績並按從高到低排序(成績去重)

1七、查詢平均成績大於85的學生姓名和平均成績

1八、查詢生物成績不及格的學生姓名和對應生物分數

1九、查詢在全部選修了李平老師課程的學生中,這些課程(李平老師的課程,不是全部課程)平均成績最高的學生姓名

20、查詢每門課程成績最好的前兩名學生姓名

2一、查詢不一樣課程但成績相同的學號,課程號,成績

2二、查詢沒學過「葉平」老師課程的學生姓名以及選修的課程名稱;

2三、查詢全部選修了學號爲1的同窗選修過的一門或者多門課程的同窗學號和姓名;

2四、任課最多的老師中學生單科成績最高的學生姓名

37-權限管理

一、建立帳號;

1)本地帳號;

create user 'cuixiaozhao'@'localhost' identified by 'Ab123456..';

2)遠程帳號;

create user 'lijingping'@'47.95.211.12' identified by 'Ab123456..';
create user 'lijingping'@'47.95.211.%' identified by 'Ab123456..';
create user 'lijingping'@'%' identified by 'Ab123456..';

二、受權;

user;權限表明*.*
db:權限表明db1.*
tables_priv;權限表明:db1.tb1
columns_priv;權限表明:id,name,sex

1)、全部的庫名錶名;
grant all on *.* to 'cuixiaozhao'@'localhost';
grant select on *.* to 'cuixiaozhao'@'localhost';

revoke select *.* from 'egon1'@'localhost';

2)、具體庫名&表名;
grant select luffycity.* to 'cuixiaozhao'@'localhost';
grant select luffycity.employee to 'cuixiaozhao'@'localhost';
revoke select luffycity.*  from 'cuixiaozhao'@'localhost';

grant select employee.* to 'cuixiaozhao'@'localhost';
revoke select employee.*  from 'cuixiaozhao'@'localhost';

4)、字段級別;

grant select(id,name),update(age) on luffycity.employee to 'cuixiaozhao'@'localhost';

38-Navicat工具的使用

一、

圖形化Navicat For MySQL工具分享(含註冊機);

Navicat For MySQL連接:https://pan.baidu.com/s/1lrK5qImWZqpTLrC2fz3Akw 密碼:u993

Navicat For Premium 連接:https://pan.baidu.com/s/18i3zNavUDA_ezmxRey9I7g 密碼:h67c

二、圖形化Navicat For MySQL工具的使用;

Navicat For MySQL的PDF使用教程連接:https://pan.baidu.com/s/1qJJ1-surKE28XQwEgWoG_Q 密碼:u6oc

三、掌握的技能;

  • 新建鏈接
  • 新建數據庫
  • 使用數據庫
  • 新建表
  • 設計表、新增(修改)字段及約束
  • 新建查詢
  • 備份數據庫、數據表
  • 批量添加註釋Ctrl + ?鍵,取反:Ctrl + Shift + ?鍵

39-pymysql模塊之基本使用

一、pymysql初識;

那如何在python程序中操做數據庫呢?這就用到了pymysql模塊,該模塊本質就是一個套接字客戶端軟件,使用前須要事先安裝。
pip3 install pymysql

二、連接、執行SQL、關閉(遊標);

#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# __Author__:TQTL911
# Version:python3.6.6
# Time:7/27/2018 6:06 PM
import pymysql

usr = input('Username:').strip()
passwd = input('Password:').strip()

#創建連接對象;
conn = pymysql.connect(
    host = '47.95.121.155',
    port = 3306,#注意此處爲int類型;
    user = 'tqtl',
    password = 'Tqtl911!@%()123456',
    db = 'LuffyCity',
    charset = 'utf8'
)
#拿到遊標;
cursor = conn.cursor()

#執行SQL語句;
sql = 'select * from userinfo where username = "%s" and password = "%s"'%(usr,passwd)
print(sql)
rows = cursor.execute(sql)

cursor.close()
conn.close()

#運行判斷
if rows:
    print('登陸成功!')
else:
    print('登陸失敗!!!')

"""
Username:egon" -- xxxx
Password:
select * from userinfo where username = "egon" -- xxxx" and password = ""
登陸成功!
出現了SQL注入現象;
"""

40-pymysql模塊之sql注入

一、execure()之sql注入;

#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# __Author__:TQTL911
# Version:python3.6.6
# Time:7/27/2018 6:41 PM
import pymysql

user = input('Username:').strip()
passwd = input('Password:').strip()

#創建連接對象;
conn = pymysql.connect(
    host = '47.95.121.155',
    port = 3306,#注意此處爲int類型;
    user = 'tqtl',
    password = 'Tqtl911!@%()123456',
    db = 'LuffyCity',
    charset = 'utf8'
)
#拿到遊標;
cursor = conn.cursor()

#執行SQL語句;
#sql = 'select * from userinfo where username = "%s" and password = "%s"'%(user,passwd)
sql = 'select * from userinfo where username = %s and password = %s'

#rows = cursor.execute(sql)
rows = cursor.execute(sql,(user,passwd))
"""
以上方法,避免了出現SQL注入;
"""

cursor.close()
conn.close()

#運行判斷
if rows:
    print('登陸成功!')
else:
    print('登陸失敗!!!')

解決思路:

# 原來是咱們對sql進行字符串拼接;
 sql="select * from userinfo where name='%s' and password='%s'" %(user,pwd)
 print(sql)
 res=cursor.execute(sql)

#改寫爲(execute幫咱們作字符串拼接,咱們無需且必定不能再爲%s加引號了);
sql="select * from userinfo where name=%s and password=%s" #!!!注意%s須要去掉引號,由於pymysql會自動爲咱們加上
res=cursor.execute(sql,[user,pwd]) #pymysql模塊自動幫咱們解決sql注入的問題,只要咱們按照pymysql的規矩來。

41-pymysql模塊之增刪改查

一、增、刪、改:conn.commit();

#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# __Author__:TQTL911
# Version:python3.6.6
# Time:7/27/2018 6:59 PM
import pymysql

#創建連接
conn = pymysql.connect(
    host = '47.95.121.155',
    port = 3306,
    user = 'tqtl',
    password = 'Tqtl911!@%()123456',
    db = 'LuffyCity',
    charset = 'utf8'
)

#拿到數據
cursor = conn.cursor()

#執行SQL語句
#增、刪、改
sql = 'insert into userinfo(username,password) values(%s,%s)'
#rows = cursor.execute(sql,('cuixiaozhao','Ab123456.'))
rows = cursor.executemany(sql,[('cuixiaozhao','Ab123456.'),('lijingping','123'),('gaozhifen','456'),('cuiqingliang','111')])
print(rows)
print(cursor.lastrowid)

conn.commit()

#關閉連接
cursor.close()
conn.close()


#查詢操做;
import pymysql

#創建連接
conn = pymysql.connect(
    host = '47.95.121.155',
    port = 3306,
    user = 'tqtl',
    password = 'Tqtl911!@%()123456',
    db = 'LuffyCity',
    charset = 'utf8'
)

#拿到數據
#cursor = conn.cursor()#元組形式展現;
cursor = conn.cursor(pymysql.cursors.DictCursor)#字典形式顯示;

#執行SQL語句
#查詢
rows =cursor.execute('select * from userinfo;')

print(cursor.fetchone())#取出1個;
print(cursor.fetchone())
print(cursor.fetchone())
print(cursor.fetchone())

#print(cursor.fetchmany(3))#取出n個;
#print(cursor.fetchall())#取出全部;

#移動光標
cursor.scroll(3,mode='absolute')#相對絕對位置移動
cursor.scroll(2,mode='relative')#相對當前位置移動
#關閉連接
cursor.close()
conn.close()

42-MySQL內置功能介紹

一、視圖、觸發器、存儲過程、事務、函數及流程控制、索引原理;

43-視圖

一、視圖初識;

  數據庫中的視圖是一個虛擬表,同真實的表同樣,視圖包含一系列帶有名稱的行和列數據。行和列數據來自由定義視圖查詢所引用的表,而且在引用視圖時候動態生成。

二、視圖的使用說明;

使用視圖咱們能夠把查詢過程當中的臨時表摘出來,用視圖去實現,這樣之後再想操做該臨時表的數據時就無需重寫複雜的sql了,
直接去視圖中查找便可,但視圖有明顯地效率問題,而且視圖是存放在數據庫中的,
若是咱們程序中使用的sql過度依賴數據庫中的視圖,即強耦合,那就意味着擴展sql極爲不便,
所以並不推薦使用。

三、視圖的建立與使用;

#語法:CREATE VIEW 視圖名稱 AS  SQL語句
create view teacher_view as select tid from teacher where tname='李平老師';

#因而查詢李平老師教授的課程名的sql能夠改寫爲
mysql> select cname from course where teacher_id = (select tid from teacher_view);
+--------+
| cname  |
+--------+
| 物理   |
| 美術   |
+--------+
rows in set (0.00 sec)

#!!!注意注意注意:
#1. 使用視圖之後就無需每次都重寫子查詢的sql,可是這麼效率並不高,還不如咱們寫子查詢的效率高;

#2. 並且有一個致命的問題:視圖是存放到數據庫裏的,若是咱們程序中的sql過度依賴於數據庫中存放的視圖,
那麼意味着,一旦sql須要修改且涉及到視圖的部分,則必須去數據庫中進行修改,而一般在公司中數據庫有專門的DBA負責,
你要想完成修改,必須付出大量的溝通成本DBA可能纔會幫你完成修改,極其地不方便

四、修改視圖;

 

五、刪除視圖;

44-觸發器

一、觸發器概念初識(一碰就動);

45-存儲過程

46-應用程序與數據庫結合使用的三種方式

47-事務

48-函數與流程控制

49-索引原理

相關文章
相關標籤/搜索