數據庫相關--mysql常用命令彙總

 

  本文對MySQL的常用命令進行分類彙總、命令介紹、舉例說明,如轉載或引用請在醒目位置放上本文連接。

  本文可作爲常用工具收藏,如對您略有幫助請點贊👍👍👍支持!

  由於SQL屬於類B的語言,不區分大小寫,爲了便於閱讀,本文所有SQL命令,均使用小寫,勿噴🙏。

 

常用命令分類:

  服務層面:包含服務的啓動、關閉等,通俗的說是進入MySQL之前,在終端輸入、與MySQL有關的命令;

  數據庫層面:包含數據庫的建立、刪除等;

  數據表層面:包含表的建立、屬性修改等,屬於項目前期數據表設計相關的命令;

  數據層面:包含數據的增、刪、改、查,屬於常用的命令;

 

說明:   

 

  [內容、參數]  -----    是指可選參數

 

 

 

一、服務層面命令(簡要的,不涉及端口、安全性等參數)

  1、啓動、停止、重啓MySQL服務:

 

# win系統
>net start mysql    # 啓動
>net stop mysql    # 停止

# ox系統,如果提示找不到命令,可直接進入安裝目錄的bin文件夾內運行命令
$ mysql.server start # 通過brew安裝的MySQL 啓動
$ mysql.server stop    # 停止
$ mysql.server restart    # 重啓

# Linux系統,如果提示找不到命令,可直接進入安裝目錄的bin文件夾內運行命令
$ path_mysql/init.d/mysqld start    # 啓動  path_mysql是指安裝路徑
$ path_mysql/init.d/mysqld stop    # 停止
$ path_mysql/init.d/mysqld restart     # 重啓

# 通過service 操作
$ service mysqld start    # 啓動
$ service mysqld stop    # 停止
$ service mysqld restart    # 重啓
$ service mysql status # 查看服務狀態

 

 

 

 

  2、首次安裝,啓動配置服務,win系統參考這裏

# ox系統
$ mysql_secure_installation

 

  3、首次登陸(新安裝,未進行配置)

# win系統
>mysql -hlocalhost -uroot

# ox系統
$mysql -uroot

  4、登陸

mysql -u用戶名 -p密碼             # (密碼)可省略,回車後再輸入,如不省略,注意-p和密碼間沒有空格

例如:mysql -uroot -pmypasswd

  5、導出/導入數據庫文件(待更新)

 

 

 

二、數據庫層面

  1、操作命令

    

命令 簡寫 具體含義
\? 顯示幫助信息
clear \c 明確當前輸入語句
connect \r 連接到服務器,可選參數爲數據庫和主機
delimiter \d 設置語句分隔符
ego \G 發送命令到MySQL服務器,並顯示結果
exit \q 退出MySQL
go \g 發送命令到MySQL服務器
help \h 顯示幫助信息
notee \t 不寫輸出文件
print \p 打印當前命令
prompt \R 改變MySQL提示信息
quit \q 退出MySQL
rehash \# 重建完成散列
source \. 執行一個SQL腳本文件,以一個文件名作爲參數
status \s 從服務器獲取MySQL的狀態信息
tee \T 設置輸出文件,並將信息添加到所有給定的輸出文件
use \u 用另一個數據庫
charset \C 切換到另一個字符集
warning \W 每個語句之後顯示警告
nowarning \w 每個語句之後不顯示警告

 

 

  

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

  2、常用命令

 

mysql>show databases;    # 查看已有的數據庫

mysql>create database 數據庫名稱 [dafault character set utf8];    # 創建[字符編碼爲utf8的]數據庫

mysql>show create database 數據庫名稱;    # 顯示新創建的數據庫信息

mysql>alter database 數據庫名稱 default character set gbk  collate gbk_bin;    #將數據庫的編碼格式設爲 gbk 同時注意最後是設爲gbk_bin,如果改爲utf8,則最後是utf8_bin

mysql>drop database  數據庫名稱;    # 刪除數據庫

mysql>use 數據庫名稱;    # 切換至數據庫     同 \u [數據庫名稱]    注意:使用簡寫命令時最後不要加 ; 
mysql>select database(); # 顯示當前所在的數據庫

 

 

 

   舉例如下:

 

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

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


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


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

 

 

 

 

三、數據表層面

 

   1、常用命令

mysql>show tables;    # 顯示當前數據庫下所有數據表

mysql>create table 表名 (
字段名1      數據類型   [完整性約束條件],
字段名2     數據類型   [完整性約束條件],
字段名3      數據類型   [完整性約束條件],
..........
)[engine=innodb];    # 創建數據表  [引擎類型,默認innodb]

mysql>show create table 表名; # 顯示數據表的基本信息,含字段及其屬性、引擎、字符集等

mysql>desc 表名;    # 顯示數據表信息,顯示字段及其屬性

mysql>alter table 原表名 rename to 新表名;    # 修改數據表名

mysql>alter table 表名 change 原字段名 新字段名 新數據屬性;    # 修改表中字段

mysql>alter table 表名 modify 字段名 數據類型;    # 修改表中字段屬性

mysql>alter table 表名 add 新字段名 數據類型 [約束條件];    # 添加新字段

mysql>alter table 表名 drop 字段名;    # 刪除字段  (慎重!!!一般使用邏輯刪除)

mysql>drop table 表名;   # 刪除數據表    (慎重!!!)

 

 

  2、舉例說明

 

mysql> show tables;           # 顯示所有數據表

+------------------+
| Tables_in_school |
+------------------+
| class            |
| graduate         |
| student          |
| teacher          |
+------------------+
4 rows in set (0.00 sec)
 
mysql> create table test(             # 新建數據表,engine=innodb可省略
    -> id int(100) unsigned not null primary key auto_increment,
    -> age int(100)
    -> )engine=innodb;
Query OK, 0 rows affected (0.03 sec)
 
mysql> show create table test;           # 顯示數據表詳細信息
+-----------------+
| Table | Create Table                                                                                                                                                     |
+----------+
| test  | CREATE TABLE `test` (
  `id` int(100) unsigned NOT NULL AUTO_INCREMENT,
  `age` int(100) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 |
+--------------+
1 row in set (0.01 sec)
 
mysql> desc test;                        # 顯示數據表字段信息
+-------+-------------------+------+-----+---------+----------------+
| Field | Type              | Null | Key | Default | Extra          |
+-------+-------------------+------+-----+---------+----------------+
| id    | int(100) unsigned | NO   | PRI | NULL    | auto_increment |
| age   | int(100)          | YES  |     | NULL    |                |
+-------+-------------------+------+-----+---------+----------------+
2 rows in set (0.00 sec)
 
mysql> alter table test rename to test1;              # 重命名數據表
Query OK, 0 rows affected (0.01 sec)

 mysql> show tables;
+------------------+
| Tables_in_school |
+------------------+
| class            |
| graduate         |
| student          |
| teacher          |
| test1            |
+------------------+
5 rows in set (0.00 sec)
mysql> alter table test1 change age birthday date not null;      # 修改數據表字段,含字段名和字段屬性
Query OK, 0 rows affected (0.03 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> desc test1;
+----------+-------------------+------+-----+---------+----------------+
| Field    | Type              | Null | Key | Default | Extra          |
+----------+-------------------+------+-----+---------+----------------+
| id       | int(100) unsigned | NO   | PRI | NULL    | auto_increment |
| birthday | date              | NO   |     | NULL    |                |
+----------+-------------------+------+-----+---------+----------------+
2 rows in set (0.00 sec)
 
mysql> alter table test1 modify birthday datetime;            # 修改字段屬性
Query OK, 0 rows affected (0.03 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> desc test1;
+----------+-------------------+------+-----+---------+----------------+
| Field    | Type              | Null | Key | Default | Extra          |
+----------+-------------------+------+-----+---------+----------------+
| id       | int(100) unsigned | NO   | PRI | NULL    | auto_increment |
| birthday | datetime          | YES  |     | NULL    |                |
+----------+-------------------+------+-----+---------+----------------+
2 rows in set (0.00 sec)


mysql> alter table test1 drop birthday;                 # 刪除字段
Query OK, 0 rows affected (0.02 sec)
Records: 0  Duplicates: 0  Warnings: 0
 

mysql> desc test1;
+-------+-------------------+------+-----+---------+----------------+
| Field | Type              | Null | Key | Default | Extra          |
+-------+-------------------+------+-----+---------+----------------+
| id    | int(100) unsigned | NO   | PRI | NULL    | auto_increment |
+-------+-------------------+------+-----+---------+----------------+
1 row in set (0.00 sec)


mysql> drop table test1;                             # 刪除數據表
Query OK, 0 rows affected (0.01 sec)
mysql> show tables;
+------------------+
| Tables_in_school |
+------------------+
| class            |
| graduate         |
| student          |
| teacher          |
+------------------+
4 rows in set (0.00 sec)

 

 

 

四、數據層面

 

  1、常用命令

mysql>insert into 表名 [字段名1,字段名2,....]  values
(值1,值2,.......),
(值1,值2,.......),
(值1,值2,.......)
........
;     # 如使用字段,則添加的每條記錄的值必須與字段一一對應;如不指定字段,則屬於按位置添加數據,每條記錄的值須同數據表中所有字段一一對應

mysql>update 表名 set 
字段名1=值1,
字段名2=值2,
....  
[where 條件];    # 更新/更改數據:[條件限制,如不加條件,則默認所有記錄的該字段均修改]

mysql>alert table 表1名 add foreign key(字段1名) references 表2名(字段2名);    # 爲表1的字段1添加外鍵,連接表2的字段2,外鍵可選約束條件作爲參數

mysql>alert table 表名 drop foreign key 字段名;    # 刪除外鍵

mysql>create [unique | fulltext | spatial] index 索引名 on 表名(字段名[asc | desc]);    # 創建索引,索引會提高查找速度,但是會增加物理開銷

mysql>drop index 索引名 on 表名;    # 刪除索引

mysql>delete from 表名 [where 條件];# 刪除表中數據[條件限制,如無條件,則清空數據表]

mysql>truncate table 表名;    # 清空數據表

mysql>select 字段名1,字段名2,...... from 表名;    # 查看錶中數據,如查看所有數據使用  select * from 表名 ,這是數據查看的基本形式,後面的例子中會有拓展

 

 

  2、舉例說明

 

mysql> alter table student add foreign key(class) references class(cid);     # 添加外鍵,如果表中有數據,則會添加失敗

Query OK, 0 rows affected (0.03 sec)

Records: 0  Duplicates: 0  Warnings: 0

 

mysql> create index sid_index on student(sid);          # 創建索引

Query OK, 0 rows affected (0.02 sec)

Records: 0  Duplicates: 0  Warnings: 0

 

mysql> show create table student;

+-----------------+

| Table   | Create Table                                                                                                                        

+-----------------+

| student | CREATE TABLE `student` (

  `sid` int(10) unsigned NOT NULL AUTO_INCREMENT,

  `name` varchar(10) NOT NULL,

  `gender` char(1) NOT NULL,

  `age` int(3) unsigned NOT NULL,

  `birthday` datetime NOT NULL,

  `phone` varchar(11) DEFAULT NULL,

  `class` int(10) unsigned NOT NULL,

  `grade` int(10) unsigned NOT NULL,

  PRIMARY KEY (`sid`),

  KEY `sid_index` (`sid`),    # 索引在這裏

  KEY `class` (`class`),

  CONSTRAINT `student_ibfk_1` FOREIGN KEY (`class`) REFERENCES `class` (`cid`)            # 這裏顯示外鍵的名稱:student_ibfk_1,刪除的時候要用這個字段

) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8 |

+-----------+

1 row in set (0.00 sec)

 

mysql> insert into class values           # 添加數據,先添加class表數據,注意:如果存在外鍵,則外鍵所指向的數據表不能爲空,否則無法添加數據

    -> (1,'10級1班',1,45,'東教學樓1層'),

    -> (2,'09級1班',2,48,'東教學樓2層'),

    -> (3,'09級2班',2,50,'東教學樓2層'),

    -> (4,'08級1班',3,51,'東教學樓3層'),

    -> (5,'08級2班',4,49,'東教學樓3層');

Query OK, 5 rows affected (0.01 sec)

Records: 5  Duplicates: 0  Warnings: 0

 

mysql> insert into student values             # 再添加student表數據

    -> (1,'李傑','男',21,'1990-1-2',13012345678,1,1),

    -> (2,'王倩','女',22,'1989-4-21',15212345678,1,1),

    -> (3,'張大力','男',20,'1991-2-12',NULL,2,2),

    -> (4,'王曉紅','女',20,'1991-7-5',18900001111,2,2),

    -> (5,'周大寶','男',21,'1990-12-23',NULL,3,2),

    -> (6,'王志剛','男',22,'1989-10-10',NULL,3,2),

    -> (7,'劉明','男',21,'1990-11-30',15912345678,4,3),

    -> (8,'郭芙蓉','女',20,'1991-6-17',NULL,4,3),

    -> (9,'李飛','男',23,'1988-12-3',13212345678,5,3),

    -> (10,'蘇潔','女',25,'1986-5-16',NULL,5,3);

Query OK, 10 rows affected (0.00 sec)

Records: 10  Duplicates: 0  Warnings: 0

 

mysql> select * from student;                #  查詢student 中所有數據

+-----+-----------+--------+-----+---------------------+-------------+-------+-------+

| sid | name      | gender | age | birthday            | phone       | class | grade |

+-----+-----------+--------+-----+---------------------+-------------+-------+-------+

|   1 | 李傑      | 男     |  21 | 1990-01-02 00:00:00 | 13012345678 |     1 |     1 |

|   2 | 王倩      | 女     |  22 | 1989-04-21 00:00:00 | 15212345678 |     1 |     1 |

|   3 | 張大力    | 男     |  20 | 1991-02-12 00:00:00 | NULL        |     2 |     2 |

|   4 | 王曉紅    | 女     |  20 | 1991-07-05 00:00:00 | 18900001111 |     2 |     2 |

|   5 | 周大寶    | 男     |  21 | 1990-12-23 00:00:00 | NULL        |     3 |     2 |

|   6 | 王志剛    | 男     |  22 | 1989-10-10 00:00:00 | NULL        |     3 |     2 |

|   7 | 劉明      | 男     |  21 | 1990-11-30 00:00:00 | 15912345678 |     4 |     3 |

|   8 | 郭芙蓉    | 女     |  20 | 1991-06-17 00:00:00 | NULL        |     4 |     3 |

|   9 | 李飛      | 男     |  23 | 1988-12-03 00:00:00 | 13212345678 |     5 |     3 |

|  10 | 蘇潔      | 女     |  25 | 1986-05-16 00:00:00 | NULL        |     5 |     3 |

+-----+-----------+--------+-----+---------------------+-------------+-------+-------+

10 rows in set (0.00 sec)

 

mysql> select sid,name,gender,age as '年齡' from student where class=3 and grade=2;   

# 條件查詢,查詢class=3 & grade=2的學生sid、name、gender、age,並將age重命名

+-----+-----------+--------+--------+

| sid | name      | gender | 年齡   |

+-----+-----------+--------+--------+

|   5 | 周大寶    | 男     |     21 |

|   6 | 王志剛    | 男     |     22 |

+-----+-----------+--------+--------+

2 rows in set (0.01 sec)

 

 

# 查詢王倩同學的上課地點,顯示姓名、性別及地點

mysql> select s.name,s.gender,c.location         # 使用數據表簡稱獲取響應的字段,如果該字段在所有使用的數據表中唯一,則可以不帶表名,直接寫字段

    -> from student as s,class as c            # 多表查詢時,通常將每個表重命名爲簡稱

    -> where s.class=c.cid                # 多表查詢的連接依據

    -> and s.name='王倩';                  # 附加查詢條件

+--------+--------+------------------+

| name   | gender | location         |

+--------+--------+------------------+

| 王倩   | 女     | 東教學樓1層      |

+--------+--------+------------------+

1 row in set (0.01 sec)

 

# 查看2年級的男女數量

mysql> select gender,count(*) from student where grade=2 group by gender;  # 使用group by實現分組 count()是聚合函數

+--------+----------+

| gender | count(*) |

+--------+----------+

| 女     |        1 |

| 男     |        3 |

+--------+----------+

2 rows in set (0.01 sec)

 

mysql> select gender,count(*) from student where grade=2 group by gender having gender='男'; 

# group by 後面可以加條件語句having,having可以使用聚合函數,而where是不可以的

 

+--------+----------+

| gender | count(*) |

+--------+----------+

| 男     |        3 |

+--------+----------+

1 row in set (0.01 sec)

 

 

 

# 查詢人數大於2的年級中,顯示年級、人數、各年級的學生平均年齡、男生數量,並安裝平均年齡倒序顯示

mysql> select grade,count(*),avg(age),count(gender='男')

    -> from student

    -> group by grade

    -> having count(*)>2 and count(gender='男')

    -> order by avg(age) desc;

+-------+----------+----------+---------------------+

| grade | count(*) | avg(age) | count(gender='男')  |

+-------+----------+----------+---------------------+

|     3 |        4 |  22.2500 |                   4 |

|     2 |        4 |  20.7500 |                   4 |

+-------+----------+----------+---------------------+

2 rows in set (0.00 sec)

 

 

 

 

 

 

 

一個常用的查詢結構:

 

查詢語句                                                     執行順序

select [distinct] * | 字段1,字段2,..| 聚合函數               ⑤

from 表1 as a,表2 as b .....               ①
join on a.id=b.id .......                  ②

where 字段|isfull [= > < is not in like between and or ]  值 (子查詢).....      ③

group by 字段                  ④

having  條件  [聚合函數]order by 字段 | [聚合函數]   [asc | desc]    ⑦

limit [offset] 數量;          ⑧


                                    ⑨  展示結果

 

 

 

 

 

 

參考資料:《MySQL數據庫入門》

 

 

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