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 AB 公司開發,目前屬於 Oracle 旗下公司。MySQL 最流行的關係型數據庫管理系統,在 WEB 應用方面MySQL是最好的 RDBMS (Relational Database Management System,關係數據庫管理系統) 應用軟件之一。linux
1)MySQL是什麼?正則表達式
mysql就是一個基於socket編寫的C/S架構的軟件; 客戶端軟件 mysql自帶:如mysql命令,mysqldump命令等; python模塊:如pymysql;
2)數據庫管理軟件分類sql
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
http://www.javashuo.com/article/p-mmjxepcq-k.html
http://www.javashuo.com/article/p-zxuckyyl-bb.html
https://www.2cto.com/database/201803/732822.html
http://www.javashuo.com/article/p-rkdcqswc-be.html
一、Windows平臺下(MySQL5.7在Windows平臺下,默認就是統一爲utf8):
一、先備份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>
參考博文:https://www.jb51.net/article/136343.htm
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;
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#不推薦使用通配符*;
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>
對數據庫進行查詢和修改的操做語言叫作SQL。SQL的含義是「結構化查詢語言」-structured Query Language。
SQL包含以下4個部分:
博文參考: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>
1)咱們知道,現實生活中咱們用來存儲數據的文件有不一樣的類型,每種文件類型對應各自不一樣的處理機制:好比處理文本用txt類型,處理表格用excel,處理圖片用png等;
2)數據庫中的表也應該有不一樣的類型,表的類型不一樣,會對應mysql不一樣的存取機制,表類型又稱爲存儲引擎;
3)存儲引擎說白了就是如何存儲數據、如何爲存儲的數據創建索引和如何更新、查詢數據等技術的實現方
法。由於在關係數據庫中數據的存儲是以表的形式存儲的,因此存儲引擎也能夠稱爲表類型(即存儲和
操做此表的類型)
4)在Oracle 和SQL Server等數據庫中只有一種存儲引擎,全部數據存儲管理機制都是同樣的。而MySql
數據庫提供了多種存儲引擎。用戶能夠根據不一樣的需求爲數據表選擇不一樣的存儲引擎,用戶也能夠根據
本身的須要編寫本身的存儲引擎
SQL 解析器、SQL 優化器、緩衝池、存儲引擎等組件在每一個數據庫中都存在,但不是每 個數據庫都有這麼多存儲引擎。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>
表至關於文件,表中的一條記錄就至關於文件的一行內容,不一樣的是,表中的一條記錄有對應的標題,稱爲表的字段;
語法:
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;
DESCRIBE userinfo; DESC userinfo; SHOW CREATE TABLE userinfo\G;
語法: 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 新字段名 新數據類型 [完整性約束條件...];
一、複製表結構和記錄;複製表結構+記錄 (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;
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>
1)整數類型
tinyint[(m)] [unsigned] [zerofill]
int[(m)][unsigned][zerofill]
int[(m)][unsigned][zerofill]
bigint[(m)][unsigned][zerofill]
2)浮點小數數據類型
定義:單精度浮點數(非準確小數值),m是數字總個數,d是小數點後個數。m最大值爲255,d最大值爲30
精確度:**** 隨着小數的增多,精度變得不許確 ****
用法:FLOAT[(M,D)] [UNSIGNED] [ZEROFILL]
定義:雙精度浮點數(非準確小數值),m是數字總個數,d是小數點後個數。m最大值爲255,d最大值爲30
精確度:****隨着小數的增多,精度比float要高,但也會變得不許確 ****
用法:DOUBLE[(M,D)] [UNSIGNED] [ZEROFILL]
3)定點小數類型
定義:準確的小數值,m是數字總個數(負號不算),d是小數點後個數。 m最大值爲65,d最大值爲30。
精確度:**** 隨着小數的增多,精度始終準確 ****,
對於精確數值計算時須要用此類型
decaimal可以存儲精確值的緣由在於其內部按照字符串存儲。
============注意啦,注意啦,注意啦=========== 1. 單獨插入時間時,須要以字符串的形式,按照對應的格式插入;如'2018' 2. 插入年份時,儘可能使用4位值; 3. 插入兩位年份時,<=69,以20開頭,好比50, 結果2050 >=70,以19開頭,好比71,結果1971
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語句中沒有指定該列的更新值,則默認更新爲當前時間。
#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) 檢索: 尾部有空格會保存下來,在檢索或者說查詢時,也會正常顯示包含空格在內的內容
一、大多數狀況下,通常用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**16 − 1)個字符。 mediumtext:A TEXT column with a maximum length of 16,777,215 (2**24 − 1) characters. longtext:A TEXT column with a maximum length of 4,294,967,295 or 4GB (2**32 − 1) characters.
說明:字段的值,只能給給定範圍中進行選擇,如單選框,多選框;
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>
約束條件與數據類型的寬度同樣,都是可選參數
做用:用於保證數據的完整性和一致性
主要分爲:
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>
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>
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;
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>
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)
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>
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>
起始偏移量要小於等於步長的值,要否則步子太大,扯着淡了。
先設置起始偏移量,再設置步長;
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、多多對、一對一;
#一對多或稱爲多對一 三張表:出版社,做者信息,書 一對多(或多對一):一個出版社能夠出版多本書 關聯方式: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>
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>
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>
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 表名 SET 字段1 = 值1, 字段2 = 值2, WHERE CONDITION(條件); 示例: UPDATE mysql.user SET password = password('Ab123456.') WHERE user = 'root' and host = 'localhost';
語法: DELETE FROM 表名 WHERE CONDITION(條件); 示例: DELETE FROM mysql.user WHERE password = 'xxxx';
對數據庫的操做,查詢語句居多;
一、找到帶查詢的表名:from 二、拿着where指定的約束條件,去文件/表中取出一條條記錄 3、將取出的一條條記錄進行分組group by ,若是沒有group by,則總體做爲一組 4、將分組的結果進行having 過濾 5、執行select 6、進行distinct去重 7、將結果按照條件排序order by(默認asc,指定desc) 八、限制結果的顯示條數
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
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>
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>
1)分組發生在where條件以後;
2)將全部記錄按照某個相同的字段進行歸類;
3)小竅門:在「每」這個字後面的字段,就是咱們分組的依據;
4)能夠按照任意字段分組,可是分組完畢後,好比group by post,只能看到post字段,若是查看組內信息,須要藉助於聚合函數;
查看MySQL5.7默認的sql_mode;
SELECT @@global.sql_mode; SET GLOBAL sql_mode = 'ONLY_FULL_GROUP_BY';
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>
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>
語法正確,但有可能從執行順序的角度來看,不符合邏輯;
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)
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>
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的語法順序及執行順序;
SELECT * FROM employee WHERE NAME LIKE 'jin%';#like關鍵字模糊匹配; SELECT * FROM employee WHERE NAME regexp '^jin';#引入正則; SELECT * FROM employee WHERE NAME regexp '^jin.*(g|n)%';#引入正則;
#內鏈接:只取兩張表的共同部分 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>
一、練習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;
/* 數據導入: 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四、任課最多的老師中學生單科成績最高的學生姓名
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';
Navicat For MySQL連接:https://pan.baidu.com/s/1lrK5qImWZqpTLrC2fz3Akw 密碼:u993
Navicat For Premium 連接:https://pan.baidu.com/s/18i3zNavUDA_ezmxRey9I7g 密碼:h67c
Navicat For MySQL的PDF使用教程連接:https://pan.baidu.com/s/1qJJ1-surKE28XQwEgWoG_Q 密碼:u6oc
那如何在python程序中操做數據庫呢?這就用到了pymysql模塊,該模塊本質就是一個套接字客戶端軟件,使用前須要事先安裝。
pip3 install pymysql
#!/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注入現象; """
#!/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的規矩來。
#!/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()
數據庫中的視圖是一個虛擬表,同真實的表同樣,視圖包含一系列帶有名稱的行和列數據。行和列數據來自由定義視圖查詢所引用的表,而且在引用視圖時候動態生成。
使用視圖咱們能夠把查詢過程當中的臨時表摘出來,用視圖去實現,這樣之後再想操做該臨時表的數據時就無需重寫複雜的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可能纔會幫你完成修改,極其地不方便