Mysql基礎語句

SQL概述

結構化查詢語言(Structured Query Language)簡稱SQL,是一種特殊目的的編程語言,是一種數據庫查詢和程序設計語言,用於存取數據以及查詢、更新和管理關係數據庫系統;同時也是數據庫腳本文件的擴展名。

dba是數據庫管理員database administrator
dbd是數據庫開發人員database developer

SQL 是1986年10 月由美國國家標準局(ANSI)通過的數據庫語言美國標準,接着,國際標準化組織(ISO)頒佈了SQL正式國際標準。1989年4月,ISO提出了具有完整性特徵的SQL89標準,1992年11月又公佈了SQL92標準,在此標準中,把數據庫分爲三個級別:基本集、標準集和完全集。

SQL語句結構

結構化查詢語言包含6個部分:
一:數據查詢語言(DQL:Data Query Language):
其語句,也稱爲“數據檢索語句”,用以從表中獲得數據,確定數據怎樣在應用程序給出。保留字SELECT是DQL(也是所有SQL)用得最多的動詞,其他DQL常用的保留字有WHERE,ORDER BY,GROUP BY和HAVING。這些DQL保留字常與其他類型的SQL語句一起使用。
二:數據操作語言(DML:Data Manipulation Language):
其語句包括動詞INSERT,UPDATE和DELETE。它們分別用於添加,修改和刪除表中的行。也稱爲動作查詢語言。
三:事務處理語言(TPL):跟shell有點類似 由多條sql語句組成的整體
它的語句能確保被DML語句影響的表的所有行及時得以更新。TPL語句包括BEGIN TRANSACTION,COMMIT和ROLLBACK。
四:數據控制語言(DCL):
它的語句通過GRANT或REVOKE獲得許可,確定單個用戶和用戶組對數據庫對象的訪問。某些RDBMS可用GRANT或REVOKE控制對錶單個列的訪問。
五:數據定義語言(DDL):
其語句包括動詞CREATE和DROP。在數據庫中創建新表或刪除表(CREAT TABLE 或 DROP TABLE);爲表加入索引等。DDL包括許多與人數據庫目錄中獲得數據有關的保留字。它也是動作查詢的一部分。
六:指針控制語言(CCL):
它的語句,像DECLARE CURSOR,FETCH INTO和UPDATE WHERE CURRENT用於對一個或多個表單獨行的操作。([dɪˈkler] [ˈkɜ:rsə®]聲明遊標)[fɛtʃ] into獲取到

MySQL語句

關於數據庫的操作

查看數據庫:

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
4 rows in set (0.00 sec)

注:
1:information_schema這數據庫保存了MySQL服務器所有數據庫的信息。如數據庫名,數據庫的表,表欄的數據類型不訪問權限等。 [ˈskimə]
2:performance_schema 這是MySQL5.5新增的一個性能優化的引擎:命名PERFORMANCE_SCHEMA [pəˈfɔ:məns]
主要用於收集數據庫服務器性能參數。MySQL用戶是不能創建存儲引擎爲PERFORMANCE_SCHEMA的表
3:mysql庫是系統庫,裏面保存有賬戶信息,權限信息等。
4:mysql5.7增加了sys 系統數據庫,通過這個庫可以快速的瞭解系統的元數據信息
元數據是關於數據信息的數據,如數據庫名或表名,列的數據類型,或訪問權限等。

mysql> use mysql;           #進到mysql庫
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> show tables;         #查看錶
+---------------------------+
| Tables_in_mysql           |
+---------------------------+
| columns_priv              |
| db                        |
| engine_cost               |
| event                     |
| func                      |
| general_log               |
| gtid_executed             |
| help_category             |
| help_keyword              |
| help_relation             |
| help_topic                |
| innodb_index_stats        |
| innodb_table_stats        |
| ndb_binlog_index          |
| plugin                    |
| proc                      |
| procs_priv                |
| proxies_priv              |
| server_cost               |
| servers                   |
| slave_master_info         |
| slave_relay_log_info      |
| slave_worker_info         |
| slow_log                  |
| tables_priv               |
| time_zone                 |
| time_zone_leap_second     |
| time_zone_name            |
| time_zone_transition      |
| time_zone_transition_type |
| user                      |
+---------------------------+
31 rows in set (0.00 sec)

mysql> show databases \G     #以行的方式顯示
*************************** 1. row ***************************
Database: information_schema
*************************** 2. row ***************************
Database: mysql
*************************** 3. row ***************************
Database: performance_schema
*************************** 4. row ***************************
Database: sys
4 rows in set (0.00 sec)
[root@localhost ~]# mysql -e 'show databases' -uroot -p123456  #這種方式用在shell腳本
mysql: [Warning] Using a password on the command line interface can be insecure.
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
[root@localhost ~]# mysqlshow -uroot -p123456
mysqlshow: [Warning] Using a password on the command line interface can be insecure.
+--------------------+
|     Databases      |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+

創建數據庫

語法:create database 數據庫名;

創建數據庫注意事項:
1)在文件系統中,MySQL的數據存儲區將以目錄方式表示MySQL數據庫。因此,上面命令中的數據庫名字必須與操作系統的約束的目錄名字一致。例如不允許文件和目錄名中有,/,:,*,?,”,<,>,|這些符號,在MySQL數據庫名字中這些字母會被自動刪除。<遵從目錄的約束>
2)數據庫的名字不能超過64個字符,包含特殊字符的名字或者是全部由數字或保留字組成的名字必須用單引號``包起來。
3)數據庫不能重名。

創建一個test庫

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

mysql> show databases;                 
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
| test               |
+--------------------+
5 rows in set (0.00 sec)

數據庫存放目錄

[root@localhost ~]# ls /var/lib/mysql/         
auto.cnf    client-cert.pem  ibdata1      ibtmp1      mysql.sock.lock     public_key.pem   sys
ca-key.pem  client-key.pem   ib_logfile0  mysql       performance_schema  server-cert.pem  test
ca.pem      ib_buffer_pool   ib_logfile1  mysql.sock  private_key.pem     server-key.pem   test1

在這裏插入圖片描述
查看後臺執行的詳情

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

創建一個有特殊字符的數據庫

mysql> create database `HA-test`;   
Query OK, 1 row affected (0.00 sec)

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| HA-test            |
| mysql              |
| performance_schema |
| sys                |
| test               |
| test1              |
+--------------------+
7 rows in set (0.00 sec)
[root@localhost mysql]# ll
總用量 122952
-rw-r-----. 1 mysql mysql       56 10月 21 07:25 auto.cnf
-rw-------. 1 mysql mysql     1680 10月 21 07:25 ca-key.pem
-rw-r--r--. 1 mysql mysql     1112 10月 21 07:25 ca.pem
-rw-r--r--. 1 mysql mysql     1112 10月 21 07:25 client-cert.pem
-rw-------. 1 mysql mysql     1676 10月 21 07:25 client-key.pem
drwxr-x---. 2 mysql mysql       20 10月 21 12:26 HA@002dtest     #HA-test
-rw-r-----. 1 mysql mysql      351 10月 21 07:36 ib_buffer_pool
-rw-r-----. 1 mysql mysql 12582912 10月 21 07:36 ibdata1
-rw-r-----. 1 mysql mysql 50331648 10月 21 07:36 ib_logfile0
-rw-r-----. 1 mysql mysql 50331648 10月 21 07:25 ib_logfile1
-rw-r-----. 1 mysql mysql 12582912 10月 21 07:36 ibtmp1

查詢當前所在的庫,相當於linux的pwd

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

以這種方式登錄可以直接對指定的數據操作

[root@localhost test]# mysql -uroot -p123456 test       
mysql: [Warning] Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 14
Server version: 5.7.28 MySQL Community Server (GPL)

Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> select database();
+------------+
| database() |
+------------+
| test       |
+------------+
1 row in set (0.00 sec)

查詢當前時間,用戶,庫

mysql> select now(),user(),database();   
+---------------------+----------------+------------+
| now()               | user()         | database() |
+---------------------+----------------+------------+
| 2019-10-21 12:35:08 | root@localhost | test       |
+---------------------+----------------+------------+
1 row in set (0.00 sec)

刪除數據庫

mysql> drop database test;   
Query OK, 0 rows affected (0.00 sec)

使用IF EXISTS 子句以避免刪除不存在的數據庫時出現的MySQL錯誤信息

mysql> create database if not exists TEST;   #查詢TEST,如果不存在則創建
Query OK, 1 row affected (0.00 sec)

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| TEST               |
| mysql              |
| performance_schema |
| sys                |
| test1              |
+--------------------+
6 rows in set (0.00 sec)

關於表的操作
創建表:
語法:create table 表名 (字段名 類型, 字段名 類型, 字段名 類型);
查看錶相關信息:
查看錶:
要進入到數據庫再查看

mysql> use TEST;
Database changed
mysql> show tables;
Empty set (0.00 sec)

mysql> create table student(id int(20),name char(40),age int);
Query OK, 0 rows affected (0.41 sec)

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

查看錶的結構:

mysql> desc student;
+-------+----------+------+-----+---------+-------+
| Field | Type     | Null | Key | Default | Extra |
+-------+----------+------+-----+---------+-------+
| id    | int(20)  | YES  |     | NULL    |       |
| name  | char(40) | YES  |     | NULL    |       |
| age   | int(11)  | YES  |     | NULL    |       |
+-------+----------+------+-----+---------+-------+
3 rows in set (0.38 sec)

int 默認長度11

如果是沒有在use到某個庫下,需要查看錶的方法

mysql> desc TEST.student;   # 常用
+-------+----------+------+-----+---------+-------+
| Field | Type     | Null | Key | Default | Extra |
+-------+----------+------+-----+---------+-------+
| id    | int(20)  | YES  |     | NULL    |       |
| name  | char(40) | YES  |     | NULL    |       |
| age   | int(11)  | YES  |     | NULL    |       |
+-------+----------+------+-----+---------+-------+
3 rows in set (0.00 sec)
mysql> explain TEST.student;
+-------+----------+------+-----+---------+-------+
| Field | Type     | Null | Key | Default | Extra |
+-------+----------+------+-----+---------+-------+
| id    | int(20)  | YES  |     | NULL    |       |
| name  | char(40) | YES  |     | NULL    |       |
| age   | int(11)  | YES  |     | NULL    |       |
+-------+----------+------+-----+---------+-------+
3 rows in set (0.00 sec)
mysql>  show columns from TEST.student;
+-------+----------+------+-----+---------+-------+
| Field | Type     | Null | Key | Default | Extra |
+-------+----------+------+-----+---------+-------+
| id    | int(20)  | YES  |     | NULL    |       |
| name  | char(40) | YES  |     | NULL    |       |
| age   | int(11)  | YES  |     | NULL    |       |
+-------+----------+------+-----+---------+-------+
3 rows in set (0.00 sec)

會一種常用的就行

查看創建表執行了哪些命令:

mysql> show create table student \G
*************************** 1. row ***************************
       Table: student
Create Table: CREATE TABLE `student` (
  `id` int(20) DEFAULT NULL,
  `name` char(40) DEFAULT NULL,
  `age` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1
1 row in set (0.03 sec)

指定表的默認存儲引擎和字符集

mysql> create table student2(id int(20),name char(40),age int)ENGINE=MyISAM DEFAULT CHARSET=utf8;
Query OK, 0 rows affected (0.10 sec)

mysql> show create table student2 \G
*************************** 1. row ***************************
       Table: student2
Create Table: CREATE TABLE `student2` (
  `id` int(20) DEFAULT NULL,
  `name` char(40) DEFAULT NULL,
  `age` int(11) DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8
1 row in set (0.03 sec)

刪除表

mysql> drop table student2;
Query OK, 0 rows affected (0.04 sec)

禁止預讀表信息

mysql> use performance_schema;  #切換到數據庫的時候,所提示的信息
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

不想有提示可以在登錄的時候加上-A參數

[root@localhost test]# mysql -uroot -p123456  -A
mysql: [Warning] Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 15
Server version: 5.7.28 MySQL Community Server (GPL)

Copyright (c) 2000, 2019, 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> use performance_schema;
Database changed

修改表名稱alter
語法:alter table 表名 rename 新表名;
修改表需要use到表所在的庫

mysql> alter table student rename students;  #studen表名修改爲students
Query OK, 0 rows affected (0.23 sec)
mysql> show tables;
+----------------+
| Tables_in_TEST |
+----------------+
| students       |
+----------------+
1 row in set (0.01 sec)

修改表中的字段類型
語法:alter table 表名 modify 要修改的字段名 要修改的類型;

mysql> desc students;       #修改前
+-------+----------+------+-----+---------+-------+
| Field | Type     | Null | Key | Default | Extra |
+-------+----------+------+-----+---------+-------+
| id    | int(20)  | YES  |     | NULL    |       |
| name  | char(40) | YES  |     | NULL    |       |
| age   | int(11)  | YES  |     | NULL    |       |
+-------+----------+------+-----+---------+-------+
3 rows in set (0.04 sec)

mysql> alter table students modify id int(10);   #修改字段id長度
Query OK, 0 rows affected (0.11 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> desc students;    #修改後
+-------+----------+------+-----+---------+-------+
| Field | Type     | Null | Key | Default | Extra |
+-------+----------+------+-----+---------+-------+
| id    | int(10)  | YES  |     | NULL    |       |
| name  | char(40) | YES  |     | NULL    |       |
| age   | int(11)  | YES  |     | NULL    |       |
+-------+----------+------+-----+---------+-------+
3 rows in set (0.00 sec)

修改表中的字段類型和字段名稱
語法:alter table 表名 change 原字段名 新字段名 新字段類型;
查了一下官方文檔,發現mysql還真的不支持同時修改多個字段,
MODIFY [COLUMN] col_name column_definition
[FIRST | AFTER col_name]

mysql> desc students;
+-------+----------+------+-----+---------+-------+
| Field | Type     | Null | Key | Default | Extra |
+-------+----------+------+-----+---------+-------+
| id    | int(10)  | YES  |     | NULL    |       |
| name  | char(40) | YES  |     | NULL    |       |
| age   | int(11)  | YES  |     | NULL    |       |
+-------+----------+------+-----+---------+-------+
3 rows in set (0.00 sec)

mysql> alter table students change name stname char(20);  #修改name字段的長度
Query OK, 0 rows affected (0.57 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> desc students;
+--------+----------+------+-----+---------+-------+
| Field  | Type     | Null | Key | Default | Extra |
+--------+----------+------+-----+---------+-------+
| id     | int(10)  | YES  |     | NULL    |       |
| stname | char(20) | YES  |     | NULL    |       |
| age    | int(11)  | YES  |     | NULL    |       |
+--------+----------+------+-----+---------+-------+
3 rows in set (0.00 sec)

注:CHANGE 和MODIFY的區別:
CHANGE 對列進行重命名和更改列的類型,需給定舊的列名稱和新的列名稱、當前的類型。 MODIFY 可以改變列的類型,此時不需要重命名(不需給定新的列名稱)

在表中添加字段
語法:alter table 表名 add 字段名 字段類型;

mysql> alter table students add sex enum('M','W');
Query OK, 0 rows affected (0.30 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> desc students;
+--------+---------------+------+-----+---------+-------+
| Field  | Type          | Null | Key | Default | Extra |
+--------+---------------+------+-----+---------+-------+
| id     | int(10)       | YES  |     | NULL    |       |
| stname | char(20)      | YES  |     | NULL    |       |
| age    | int(11)       | YES  |     | NULL    |       |
| sex    | enum('M','W') | YES  |     | NULL    |       |
+--------+---------------+------+-----+---------+-------+
4 rows in set (0.00 sec)

指定位置添加字段
在第一列添加一個字段

mysql> alter table students add uid int(10) first;
Query OK, 0 rows affected (0.05 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> desc students;
+--------+---------------+------+-----+---------+-------+
| Field  | Type          | Null | Key | Default | Extra |
+--------+---------------+------+-----+---------+-------+
| uid    | int(10)       | YES  |     | NULL    |       |
| id     | int(10)       | YES  |     | NULL    |       |
| stname | char(20)      | YES  |     | NULL    |       |
| age    | int(11)       | YES  |     | NULL    |       |
| sex    | enum('M','W') | YES  |     | NULL    |       |
+--------+---------------+------+-----+---------+-------+
5 rows in set (0.00 sec)

在age後面添加一個address字段

mysql> alter table students add address char(40) after age;
Query OK, 0 rows affected (0.16 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> desc students;
+---------+---------------+------+-----+---------+-------+
| Field   | Type          | Null | Key | Default | Extra |
+---------+---------------+------+-----+---------+-------+
| uid     | int(10)       | YES  |     | NULL    |       |
| id      | int(10)       | YES  |     | NULL    |       |
| stname  | char(20)      | YES  |     | NULL    |       |
| age     | int(11)       | YES  |     | NULL    |       |
| address | char(40)      | YES  |     | NULL    |       |
| sex     | enum('M','W') | YES  |     | NULL    |       |
+---------+---------------+------+-----+---------+-------+
6 rows in set (0.00 sec)

刪除表中字段
語法:alter table 表名 drop 字段名 ;

mysql> alter table students drop address;
Query OK, 0 rows affected (0.15 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> desc students;
+--------+---------------+------+-----+---------+-------+
| Field  | Type          | Null | Key | Default | Extra |
+--------+---------------+------+-----+---------+-------+
| uid    | int(10)       | YES  |     | NULL    |       |
| id     | int(10)       | YES  |     | NULL    |       |
| stname | char(20)      | YES  |     | NULL    |       |
| age    | int(11)       | YES  |     | NULL    |       |
| sex    | enum('M','W') | YES  |     | NULL    |       |
+--------+---------------+------+-----+---------+-------+
5 rows in set (0.04 sec)

關於記錄的操作
插入字段<記錄>insert:
語法:insert into 表名values (字段值1,字段值2, 字段值3);

mysql> insert into students values(44,1,'zhangs',21,'m');
Query OK, 1 row affected (0.06 sec)
mysql> select * from students;
+------+------+--------+------+------+
| uid  | id   | stname | age  | sex  |
+------+------+--------+------+------+
|   44 |    1 | zhangs |   21 | M    |
+------+------+--------+------+------+
1 row in set (0.03 sec)

同時插入多條,使用,分開

mysql> insert into students (id,stname) values(4,'xie');
Query OK, 1 row affected (0.05 sec)

查詢表中記錄
語法:select * from 表名稱;

mysql> select * from students;       #  *代表所有
+------+------+--------+------+------+
| uid  | id   | stname | age  | sex  |
+------+------+--------+------+------+
|   44 |    1 | zhangs |   21 | M    |
| NULL |    4 | xie    | NULL | NULL |
+------+------+--------+------+------+
2 rows in set (0.00 sec)

當字段比較多的時候我們也可以使用\G

mysql> select * from students \G         #查看某個字段,可以指定字段查詢
*************************** 1. row ***************************
   uid: 44
    id: 1
stname: zhangs
   age: 21
   sex: M
*************************** 2. row ***************************
   uid: NULL
    id: 4
stname: xie
   age: NULL
   sex: NULL
*************************** 3. row ***************************
   uid: 23
    id: NULL
stname: xie
   age: 23
   sex: NULL
3 rows in set (0.00 sec)
mysql> select stname from students \G       
*************************** 1. row ***************************
stname: zhangs
*************************** 2. row ***************************
stname: xie
*************************** 3. row ***************************
stname: xie
3 rows in set (0.00 sec)
mysql> select uid,stname  from students \G
*************************** 1. row ***************************
   uid: 44
stname: zhangs
*************************** 2. row ***************************
   uid: NULL
stname: xie
*************************** 3. row ***************************
   uid: 23
stname: xie
3 rows in set (0.03 sec)
mysql> select uid,stname  from students;
+------+--------+
| uid  | stname |
+------+--------+
|   44 | zhangs |
| NULL | xie    |
|   23 | xie    |
+------+--------+
3 rows in set (0.00 sec)

mysql> select  * from  students where uid=44;  # 指定參數查詢
+------+------+--------+------+------+
| uid  | id   | stname | age  | sex  |
+------+------+--------+------+------+
|   44 |    1 | zhangs |   21 | M    |
+------+------+--------+------+------+
1 row in set (0.17 sec)

查看別的數據庫的表或者不在本數據庫上進行查看
語法:SELECT 字段 FROM 數據庫名.表名;

mysql> use mysql; 
Database changed
mysql> select * from TEST.students;  #跨庫查詢,查看某個數據庫下指定的表內容,數據庫名.表名
+------+------+--------+------+------+
| uid  | id   | stname | age  | sex  |
+------+------+--------+------+------+
|   44 |    1 | zhangs |   21 | M    |
| NULL |    4 | xie    | NULL | NULL |
|   23 | NULL | xie    |   23 | NULL |
+------+------+--------+------+------+
3 rows in set (0.00 sec)

查詢null值

mysql> select * from TEST.students where age is null;
+------+------+--------+------+------+
| uid  | id   | stname | age  | sex  |
+------+------+--------+------+------+
| NULL |    4 | xie    | NULL | NULL |
+------+------+--------+------+------+
1 row in set (0.30 sec)

查詢空值

mysql> select * from TEST.students where age='';
Empty set (0.00 sec)

刪除記錄

刪除id爲4的行

mysql> delete from students where id=4;
Query OK, 1 row affected (0.05 sec)

mysql> select * from students;
+------+------+--------+------+------+
| uid  | id   | stname | age  | sex  |
+------+------+--------+------+------+
|   23 | NULL | xie    |   23 | NULL |
+------+------+--------+------+------+
1 row in set (0.00 sec)

刪除sex爲空的行

mysql> delete from students where sex is null;
Query OK, 1 row affected (0.01 sec)

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

更新記錄

mysql> select * from students;
+------+------+--------+------+------+
| uid  | id   | stname | age  | sex  |
+------+------+--------+------+------+
|   23 | NULL | xie    |   23 | NULL |
|   44 |    1 | zhangs |   21 | M    |
|   45 |    2 | dz     |   21 | W    |
|    5 |    3 | dz     |   21 | W    |
+------+------+--------+------+------+
4 rows in set (0.00 sec)

mysql> update students set sex='M' where uid=23;
Query OK, 1 row affected (0.04 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> select * from students;
+------+------+--------+------+------+
| uid  | id   | stname | age  | sex  |
+------+------+--------+------+------+
|   23 | NULL | xie    |   23 | M    |
|   44 |    1 | zhangs |   21 | M    |
|   45 |    2 | dz     |   21 | W    |
|    5 |    3 | dz     |   21 | W    |
+------+------+--------+------+------+
4 rows in set (0.00 sec)

所有的id字段都變爲1

mysql> update students set id=1;
Query OK, 3 rows affected (0.00 sec)
Rows matched: 4  Changed: 3  Warnings: 0

mysql> select * from students;
+------+------+--------+------+------+
| uid  | id   | stname | age  | sex  |
+------+------+--------+------+------+
|   23 |    1 | xie    |   23 | M    |
|   44 |    1 | zhangs |   21 | M    |
|   45 |    1 | dz     |   21 | W    |
|    5 |    1 | dz     |   21 | W    |
+------+------+--------+------+------+
4 rows in set (0.00 sec)

同時更新多個字段時候用,號隔開

SQL基礎條件查詢語句

語法:select 字段名1,字段名2 from 表名 [where 條件];
查詢students表中的name,age

mysql> select stname,age from students;
+--------+------+
| stname | age  |
+--------+------+
| xie    |   23 |
| zhangs |   21 |
| dz     |   21 |
| dz     |   21 |
+--------+------+
4 rows in set (0.00 sec)

去重複查詢distinct

mysql> select distinct stname,age from students;
+--------+------+
| stname | age  |
+--------+------+
| xie    |   23 |
| zhangs |   21 |
| dz     |   21 |
+--------+------+
3 rows in set (0.30 sec)

查詢age=21的,顯示id,stname,age

mysql>  select  distinct id,stname,age from students where age=21;
+------+--------+------+
| id   | stname | age  |
+------+--------+------+
|    1 | zhangs |   21 |
|    1 | dz     |   21 |
+------+--------+------+
2 rows in set (0.00 sec)

mysql的distinct可以對*使用

mysql> select distinct * from students; 
+------+------+--------+------+------+
| uid  | id   | stname | age  | sex  |
+------+------+--------+------+------+
|   23 |    1 | xie    |   23 | M    |
|   44 |    1 | zhangs |   21 | M    |
|   45 |    1 | dz     |   21 | W    |
|    5 |    1 | dz     |   21 | W    |
+------+------+--------+------+------+
4 rows in set (0.00 sec)

mysql> select * from students;
+------+------+--------+------+------+
| uid  | id   | stname | age  | sex  |
+------+------+--------+------+------+
|   23 |    1 | xie    |   23 | M    |
|   44 |    1 | zhangs |   21 | M    |
|   45 |    1 | dz     |   21 | W    |
|    5 |    1 | dz     |   21 | W    |
+------+------+--------+------+------+
4 rows in set (0.00 sec)

使用and和or進行多條件查詢
or和and 同時存在時,先算and的兩邊值,邏輯與先執行

mysql> select id ,stname,age from students where  id>3 and age>20;
+------+--------+------+
| id   | stname | age  |
+------+--------+------+
|    8 | zhangs |   21 |
|    7 | dd     |   21 |
+------+--------+------+
2 rows in set (0.00 sec)
mysql> select id,stname,age from students where id>4 or age>21;
+------+--------+------+
| id   | stname | age  |
+------+--------+------+
|    3 | xie    |   23 |
|    8 | zhangs |   21 |
|    7 | dd     |   21 |
+------+--------+------+
3 rows in set (0.00 sec)
mysql> select * from students where stname='dd' and (age=21 or age=23);
+------+------+--------+------+------+
| uid  | id   | stname | age  | sex  |
+------+------+--------+------+------+
|   45 |    7 | dd     |   21 | W    |
+------+------+--------+------+------+
1 row in set (0.00 sec)

注意and和or都是用的時候的邏輯關係

MySQL區分大小寫查詢
Mysql查詢默認是不區分大小寫的

mysql> select stname from students where stname='dd';
+--------+
| stname |
+--------+
| dd     |
| DD     |
| DD     |
| DD     |
+--------+
4 rows in set (0.00 sec)

解決

mysql> select * from students where binary stname='dd';
+------+------+--------+------+------+
| uid  | id   | stname | age  | sex  |
+------+------+--------+------+------+
|   45 |    7 | dd     |   21 | W    |
+------+------+--------+------+------+
1 row in set (0.04 sec)

BINARY是類型轉換運算符,它用來強制它後面的字符串爲一個二進制字符串,可以理解爲在字符串比較的時候區分大小寫。

MySQL查詢排序

語法:select distinct 字段1,字段2 from 表名order by 字段名;
默認爲升序 asc

mysql> select distinct id from students order by id asc;
+------+
| id   |
+------+
|    1 |
|    3 |
|    6 |
|    7 |
|    8 |
|   11 |
+------+
6 rows in set (0.00 sec)
mysql> select distinct id from students order by id desc;
+------+
| id   |
+------+
|   11 |
|    8 |
|    7 |
|    6 |
|    3 |
|    1 |
+------+
6 rows in set (0.00 sec)

關於MySQL命令幫助

mysql> help show;
Name: 'SHOW'
Description:
SHOW has many forms that provide information about databases, tables,
columns, or status information about the server. This section describes
those following:

SHOW {BINARY | MASTER} LOGS
SHOW BINLOG EVENTS [IN 'log_name'] [FROM pos] [LIMIT [offset,] row_count]
SHOW CHARACTER SET [like_or_where]
SHOW COLLATION [like_or_where]
SHOW [FULL] COLUMNS FROM tbl_name [FROM db_name] [like_or_where]
SHOW CREATE DATABASE db_name
SHOW CREATE EVENT event_name
SHOW CREATE FUNCTION func_name
SHOW CREATE PROCEDURE proc_name
SHOW CREATE TABLE tbl_name
SHOW CREATE TRIGGER trigger_name
SHOW CREATE VIEW view_name
SHOW DATABASES [like_or_where]
SHOW ENGINE engine_name {STATUS | MUTEX}
SHOW [STORAGE] ENGINES
SHOW ERRORS [LIMIT [offset,] row_count]
SHOW EVENTS
SHOW FUNCTION CODE func_name
SHOW FUNCTION STATUS [like_or_where]
SHOW GRANTS FOR user
SHOW INDEX FROM tbl_name [FROM db_name]
SHOW MASTER STATUS
SHOW OPEN TABLES [FROM db_name] [like_or_where]
SHOW PLUGINS
SHOW PROCEDURE CODE proc_name
SHOW PROCEDURE STATUS [like_or_where]
SHOW PRIVILEGES
SHOW [FULL] PROCESSLIST
SHOW PROFILE [types] [FOR QUERY n] [OFFSET n] [LIMIT n]
SHOW PROFILES
SHOW RELAYLOG EVENTS [IN 'log_name'] [FROM pos] [LIMIT [offset,] row_count]
SHOW SLAVE HOSTS
SHOW SLAVE STATUS [FOR CHANNEL channel]
SHOW [GLOBAL | SESSION] STATUS [like_or_where]
SHOW TABLE STATUS [FROM db_name] [like_or_where]
SHOW [FULL] TABLES [FROM db_name] [like_or_where]
SHOW TRIGGERS [FROM db_name] [like_or_where]
SHOW [GLOBAL | SESSION] VARIABLES [like_or_where]
SHOW WARNINGS [LIMIT [offset,] row_count]

like_or_where:
    LIKE 'pattern'
  | WHERE expr

If the syntax for a given SHOW statement includes a LIKE 'pattern'
part, 'pattern' is a string that can contain the SQL % and _ wildcard
characters. The pattern is useful for restricting statement output to
matching values.

Several SHOW statements also accept a WHERE clause that provides more
flexibility in specifying which rows to display. See
https://dev.mysql.com/doc/refman/5.7/en/extended-show.html.

URL: https://dev.mysql.com/doc/refman/5.7/en/show.html
mysql> help select;
Name: 'SELECT'
Description:
Syntax:    #語法
SELECT  
    [ALL | DISTINCT | DISTINCTROW ]
      [HIGH_PRIORITY]
      [STRAIGHT_JOIN]
      [SQL_SMALL_RESULT] [SQL_BIG_RESULT] [SQL_BUFFER_RESULT]
      [SQL_CACHE | SQL_NO_CACHE] [SQL_CALC_FOUND_ROWS]
    select_expr [, select_expr ...]
    [FROM table_references
      [PARTITION partition_list]
    [WHERE where_condition]
    [GROUP BY {col_name | expr | position}
      [ASC | DESC], ... [WITH ROLLUP]]
    [HAVING where_condition]
    [ORDER BY {col_name | expr | position}
      [ASC | DESC], ...]
    [LIMIT {[offset,] row_count | row_count OFFSET offset}]
    [PROCEDURE procedure_name(argument_list)]
    [INTO OUTFILE 'file_name'
        [CHARACTER SET charset_name]
        export_options
      | INTO DUMPFILE 'file_name'
      | INTO var_name [, var_name]]
    [FOR UPDATE | LOCK IN SHARE MODE]]

SELECT is used to retrieve rows selected from one or more tables, and
can include UNION statements and subqueries. See [HELP UNION], and
https://dev.mysql.com/doc/refman/5.7/en/subqueries.html.

The most commonly used clauses of SELECT statements are these:

o Each select_expr indicates a column that you want to retrieve. There
  must be at least one select_expr.

o table_references indicates the table or tables from which to retrieve
  rows. Its syntax is described in [HELP JOIN].

o SELECT supports explicit partition selection using the PARTITION with
  a list of partitions or subpartitions (or both) following the name of
  the table in a table_reference (see [HELP JOIN]). In this case, rows
  are selected only from the partitions listed, and any other
  partitions of the table are ignored. For more information and
  examples, see
  https://dev.mysql.com/doc/refman/5.7/en/partitioning-selection.html.

  SELECT ... PARTITION from tables using storage engines such as MyISAM
  that perform table-level locks (and thus partition locks) lock only
  the partitions or subpartitions named by the PARTITION option.

  For more information, see
  https://dev.mysql.com/doc/refman/5.7/en/partitioning-limitations-lock
  ing.html.

o The WHERE clause, if given, indicates the condition or conditions
  that rows must satisfy to be selected. where_condition is an
  expression that evaluates to true for each row to be selected. The
  statement selects all rows if there is no WHERE clause.

  In the WHERE expression, you can use any of the functions and
  operators that MySQL supports, except for aggregate (summary)
  functions. See
  https://dev.mysql.com/doc/refman/5.7/en/expressions.html, and
  https://dev.mysql.com/doc/refman/5.7/en/functions.html.

SELECT can also be used to retrieve rows computed without reference to
any table.

URL: https://dev.mysql.com/doc/refman/5.7/en/select.html

Yum 安裝mysql5.7的方法:

CentOS 7版本下載

[root@localhost ~]# rpm -Uvh https://repo.mysql.com//yum/mysql-5.7-community/el/7/x86_64/mysql57-community-release-el7-10.noarch.rpm
[root@localhost ~]#yum list
[root@localhost ~]#yum -y install mysql-community-server

第一次通過# grep “password” /var/log/mysqld.log 命令獲取MySQL的臨時密碼
用該密碼登錄到服務端後,必須馬上修改密碼,不然操作查詢時報錯誤
剛開始設置的密碼必須符合長度,且必須含有數字,小寫或大寫字母,特殊字符。
如果想設置簡單密碼,如下操作:
方法一:首先,修改validate_password_policy參數的值

mysql> set global validate_password_policy=0;  #定義複雜度
mysql> set global validate_password_length=1;  #定義長度 默認是8
mysql>set password for 'root'@'localhost'=password('123456');
mysql> flush privileges; 

方法二:在/etc/my.cnf 可關閉密碼強度審計插件,重啓mysql服務
validate-password=ON/OFF/FORCE/FORCE_PLUS_PERMANENT: 決定是否使用該插件(及強制/永久強制使用)。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章