大纲
一、库管理
二、表管理
三、索引管理
四、用户管理
五、视图管理
六、SELECT查询
一、库管理
(1)、创建数据库CREATE DATABASE db_name [CHARACTER SET [=] charset_name] [COLLATE [=] collation_name];
mysql> CREATE DATABASE IF NOT EXISTS testdb CHARACTER SET 'gbk' COLLATE 'gbk_chinese_ci';
(2)、删除数据库
DROP DATABASE [IF EXISTS] db_name;
mysql> DROP DATABASE testdb;
(3)、查看所有数据库
SHOW DATABASES;
mysql> SHOW DATABASES;
二、表管理
(1)、创建表CREATE TABLE [IF NOT EXISTS] db_name.tb_name( col_name column_definition);
CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name select_statement
CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name { LIKE old_tbl_name | (LIKE old_tbl_name) }
mysql> CREATE TABLE user(Name CHAR(5) NOT NULL,Age TINYINT UNSIGNED,Gender ENUM('M','F') NOT NULL);
mysql> CREATE TABLE testuser SELECT User,Host,Password FROM mysql.user;
mysql> CREATE TABLE testusers LIKE mysql.user;
(2)、删除表DROP TABLE [IF EXISTS] tb_name;
mysql> DROP TABLE students;
(3)、查看表SHOW TABLES FROM db_name;
mysql> SHOW TABLES FROM testdb;
(4)、查看表结构DESC tb_name;
mysql> DESC students;
(5)、修改表字段的数据类型或者类型修饰符ALTER TABLE tb_name MODIFY [COLUMN] col_name column_definition [FIRST | AFTER col_name];
mysql> ALTER TABLE students MODIFY Course VARCHAR(10) NOT NULL AFTER Gender;
(5)、修改表字段的字段名称ALTER TABLE tb_name CHANGE old_col_name new_col_name column_definition [FIRST|AFTER col_name];
mysql> ALTER TABLE students CHANGE course Course VARCHAR(20) AFTER Name;
(6)、新增表字段ALTER TABLE tb_name ADD [COLUMN] col_name column_definition [FIRST | AFTER col_name];
mysql> ALTER TABLE students ADD course varchar(20);
(7)、删除表字段ALTER TABLE tb_name DROP [COLUMN] col_name;
mysql> ALTER TABLE students DROP Course;
(8)、修改表名称ALTER TABLE tb_name RENAME [TO|AS] new_tbl_name;
RENAME TABLE tbl_name TO new_tbl_name
mysql> ALTER TABLE Course RENAME student;
mysql> RENAME TABLE testuser TO test;
(9)、修改表的存储引擎ALTER TABLE tb_name engine engine_name;
mysql> ALTER TABLE student ENGINE Innodb;
(10)、添加唯一键ALTER TABLE tb_name ADD UNIQUE [KEY] (index_col_name,...);
mysql> ALTER TABLE Course ADD UNIQUE KEY (Name);
(11)、添加外键约束(存储引擎必须支持事务才能添加)ALTER TABLE tb_name ADD FOREIGN (index_col_name,...) REFERENCES tb_name (col_name);
mysql> ALTER TABLE Course ADD FOREIGN KEY (CID) REFERENCES student (CID);
(12)、查看表结构DESC tb_name;
mysql> DESC students;
(13)、往表中插入数据INSERT INTO tb_name [(col1,col2,...)] VALUES|VALUE ('STRING', NUM,...),('STRING',NUM,...);
mysql> INSERT INTO students VALUES ('QiaoFeng',24,'M','XiangLongshibaZhang'),
-> ('DuanYu',22,'M','LiumaiShenjian'),
-> ('XuZhu',23,'M','XiaoYaoGong'),
-> ('Murongfu',26,'M','DouzhuanXingyi');
(14)、修改表中数据UPDATE tb_name SET column=value WHERE CONDITION;
mysql> UPDATE students SET Gender='F' WHERE Name='Murongfu';
(15)、删除表中数据
DELETE FROM tb_name WHERE CONDITION;
mysql> DELETE FROM students WHERE Name='QiaoFeng';
(16)、清空表数据TRUNCATE TABLE tb_name;
mysql> TRUNCATE TABLE students;
三、索引管理
(1)、创建索引
CREATE INDEX index_name ON tb_name (index_col_name) [index_option] ...
mysql> CREATE INDEX foreign_id ON student (Name(4) DESC) USING BTREE;
(2)、删除索引
DROP [ONLINE|OFFLINE] INDEX index_name ON tbl_name
mysql> DROP INDEX foreign_id ON student;
(3)、查看索引
SHOW {INDEX | INDEXES | KEYS} {FROM | IN} tbl_name
mysql> SHOW INDEXES FROM student;
四、用户管理
(1)、创建用户CREATE USER 'USERNAME'@'HOST' [IDENTIFIED BY 'PASSWORD'];
mysql> CREATE USER 'admin'@'172.16.1.111' IDENTIFIED BY 'redhat';
(2)、删除用户
DROP USER 'USERNAME'@'HOST';
mysql> DROP USER 'admin'@'172.16.1.111';
(3)、给用户授权GRANT pri1,pri2,... ON DB_NAME.TB_NAME TO 'USERNAME'@'HOST' [IDENTIFIED BY 'PASSWORD'];
mysql> GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY 'redhat';
(4)、回收用户权限REVOKE pri1,pri2,... ON DB_NAME.TB_NAME FROM 'USERNAME'@'HOST';
mysql> REVOKE SELECT ON testdb.* FROM 'admin'@'172.16.1.103';
(5)、查看用户的授权
SHOW GRANTS FOR 'USERNAME'@'HOST';
mysql> SHOW GRANTS FOR 'admin'@'172.16.1.111';
(6)、列级别授权GRANT pri1(col_name) ON DB_NAME.TB_NAME TO 'USERNAME'@'HOST' [IDENTIFIED BY 'PASSWORD'];
mysql> GRANT UPDATE(Age) ON testdb.test TO 'admin'@'%';
(7)、用户重命名RENAME USER old_user TO new_user
RENAME USER 'admin'@'%' TO 'admin'@'172.16.1.108';
(8)、给用户加密码第一种:SET PASSWORD FOR 'USERNAME'@'HOST'=PASSWORD('NEW_PASSWORD');
mysql> SET PASSWORD FOR 'root'@'localhost'=PASSWORD('redhat');
Query OK, 0 rows affected (0.03 sec)
第二种:mysqladmin-uUSERNAME -hHOST password 'NEW_PASSWORD' -p
[root@soysauce ~]# mysqladmin -uroot -h localhost -p password 'redhat'
Enter password:
第三种:UPDATE mysql.user SET Password=PASSWORD('NEW_PASSWD') WHERE User='USERNAME' AND Host='HOST';
mysql> UPDATE mysql.user SET Password=PASSWORD('redhat') WHERE User='root';
Query OK, 4 rows affected (0.06 sec)
Rows matched: 4 Changed: 4 Warnings: 0
mysql> FLUSH PRIVILEGES;
Query OK, 0 rows affected (0.00 sec)
mysql> exit
Bye
(9)、忘记mysql管理员密码[root@soysauce ~]# service mysqld stop
Shutting down MySQL. SUCCESS!
[root@soysauce ~]# mysqld_safe --skip-grant-tables --skip-networking &
[1] 50967
[root@soysauce ~]# 151224 21:31:23 mysqld_safe Logging to '/data/mysql/soysauce.err'.
151224 21:31:23 mysqld_safe Starting mysqld daemon with databases from /data/mysql
[root@soysauce ~]# mysql
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 1
Server version: 5.5.28-log MySQL Community Server (GPL)
Copyright (c) 2000, 2013, 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> UPDATE mysql.user SET Password=PASSWORD('redhat') WHERE User='root' AND Host='localhost';
Query OK, 0 rows affected (0.07 sec)
Rows matched: 1 Changed: 0 Warnings: 0
mysql> FLUSH PRIVILEGES;
Query OK, 0 rows affected (0.14 sec)
mysql> exit
Bye
[root@soysauce ~]# service mysqld stop
Shutting down MySQL.151224 21:32:46 mysqld_safe mysqld from pid file /data/mysql/soysauce.pid ended
SUCCESS!
[1]+ Done mysqld_safe --skip-grant-tables --skip-networking
[root@soysauce ~]# service mysqld start
Starting MySQL.. SUCCESS!
[root@soysauce ~]# mysql -uroot -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 1
Server version: 5.5.28-log MySQL Community Server (GPL)
Copyright (c) 2000, 2013, 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>
五、视图管理
(1)、创建视图CREATE VIEW view_name [(column_list)] AS select_statement
mysql> CREATE VIEW stu AS SELECT * FROM students LIMIT 5;
(2)、删除视图
DROP VIEW [IF EXISTS] view_name [, view_name] ...
mysql> DROP VIEW stu;
六、SELECT查询
1、单表查询(简单查询)
(1)、选择SELECT * FROM tb_name;
mysql> SELECT * FROM students WHERE Age>=20;
(2)、投影SELECT field1,field2 FROM tb_name;
mysql> SELECT Name,Age FROM students;
(3)、选择加投影SELECT [DISTINCT] * FROM tb_name WHERE qualification;
mysql> SELECT Name,Age FROM students WHERE Age >= 20;
(4)、相同的值只显示一次SELECT [DISTINCT] * FROM tb_name WHERE qualification;
mysql> SELECT DISTINCT Gender FROM students;
(5)、比较运算符
>:大于
<=:小于等于
>=:大于等于
=:等于
!=:不等于
mysql> SELECT * FROM students WHERE Age>=20;
(6)、组合条件查询AND:逻辑与
OR:逻辑或
NOT:逻辑非
mysql> SELECT * FROM students WHERE Age>20 AND Gender='M';
mysql> SELECT * FROM students WHERE Age>20 OR Gender='M';
mysql> SELECT * FROM students WHERE NOT Age>20;
mysql> SELECT * FROM students WHERE NOT (Age>20 OR Gender='M');
(7)、两数值之间BETWEEN value1 AND value2
mysql> SELECT * FROM students WHERE Age BETWEEN 20 AND 25;
(8)、基于通配或正则做条件匹配LIKE 'wildcard'
%:任意长度的任意字符
_:任意单个字符
RLIKE 'REGEXP'
mysql> SELECT * FROM students WHERE Name LIKE 'y%';
mysql> SELECT * FROM students WHERE Name LIKE 'y____';
mysql> SELECT * FROM students WHERE Name LIKE '%ing%';
mysql> SELECT * FROM students WHERE Name RLIKE '^[XY].*';
mysql> SELECT * FROM students WHERE Age RLIKE '(18|20|25)';
(9)、判断是否为空或不空IS NOT NULL:不为空
IS NULL:为空
mysql> SELECT * FROM students WHERE CID2 IS NULL;
mysql> SELECT * FROM students WHERE CID2 IS NOT NULL;
(10)、离散列表表示IN (value1,value2...)
mysql> SELECT * FROM students WHERE Age IN (18,20,25);
(11)、查询结果排序ORDER BY field_name {ASC|DESC}
mysql> SELECT * FROM students WHERE CID2 IS NOT NULL ORDER BY Age DESC;
(12)、别名col_name AS Alias
mysql> SELECT Name AS Student_Name FROM students;
(13)、LIMITLIMIT [offset,]Count
mysql> SELECT Name AS Student_Name FROM students LIMIT 2; # 显示2个
mysql> SELECT Name AS Student_Name FROM students LIMIT 2,3; # 偏移量为2,往后取3个
(14)、聚合SUM():和
MIN():最小值
MAX():最大值
AVG():平均数
COUNT():总个数
mysql> SELECT SUM(Age) FROM students;
mysql> SELECT MAX(Age) FROM students;
mysql> SELECT MIN(Age) FROM students;
mysql> SELECT AVG(Age) FROM students;
mysql> SELECT COUNT(Age) FROM students;
(15)、分组
GROUP BY [HAVING where_condition]
mysql> SELECT Gender,AVG(Age) FROM students GROUP BY Gender;
mysql> SELECT CID1,COUNT(CID1) AS Persons FROM students GROUP BY CID1;
mysql> SELECT CID1,COUNT(CID1) AS Persons FROM students GROUP BY CID1 HAVING Persons>=2;
2、多表查询
(1)、笛卡尔积(交叉连接)mysql> SELECT * FROM students,courses;
(2)、自然连接mysql> SELECT students.Name,courses.Cname FROM students,courses WHERE students.CID1 = courses.CID;
mysql> SELECT s.Name,c.Cname FROM students AS s,courses AS c WHERE s.CID1 = c.CID;
(3)、左外连接mysql> SELECT s.Name,c.Cname FROM students AS s LEFT JOIN courses AS c ON s.CID1 = c.CID;
+--------------+------------------+
| Name | Cname |
+--------------+------------------+
| GuoJing | TaiJiquan |
| YangGuo | TaiJiquan |
| DingDian | Qishangquan |
| HuFei | Wanliduxing |
| HuangRong | Qianzhuwandushou |
| YueLingshang | Wanliduxing |
| ZhangWuji | Hamagong |
| Xuzhu | TaiJiquan |
| LingHuchong | NULL |
| YiLin | NULL |
+--------------+------------------+
10 rows in set (0.00 sec)
(4)、右外连接mysql> SELECT s.Name,c.Cname FROM students AS s RIGHT JOIN courses AS c ON s.CID1 = c.CID;
+--------------+------------------+
| Name | Cname |
+--------------+------------------+
| ZhangWuji | Hamagong |
| GuoJing | TaiJiquan |
| YangGuo | TaiJiquan |
| Xuzhu | TaiJiquan |
| NULL | Yiyangzhi |
| NULL | Jinshejianfa |
| HuangRong | Qianzhuwandushou |
| DingDian | Qishangquan |
| NULL | Qiankundanuoyi |
| HuFei | Wanliduxing |
| YueLingshang | Wanliduxing |
| NULL | Pixiejianfa |
| NULL | Jiuyinbaiguzhua |
+--------------+------------------+
13 rows in set (0.00 sec)
(5)、自连接
mysql> SELECT s.Name AS Stu,c.Name AS Teacher FROM students AS s,students AS c WHERE s.TID = c.SID;
+-----------+-------------+
| Stu | Teacher |
+-----------+-------------+
| GuoJing | DingDian |
| YangGuo | GuoJing |
| DingDian | ZhangWuji |
| HuFei | HuangRong |
| HuangRong | LingHuchong |
+-----------+-------------+
5 rows in set (0.00 sec)
3、子查询比较操作中使用子查询:子查询只能返回单个值
mysql> SELECT Name FROM students WHERE Age > (SELECT AVG(Age) FROM students);
mysql> SELECT Name FROM students WHERE Age IN (SELECT Age FROM tutors);
mysql> SELECT s.Name FROM students AS s WHERE s.CID2 IN (SELECT CID FROM courses);
mysql> SELECT Name FROM (SELECT Name,Age FROM students) AS t WHERE t.Age >= 20;
mysql> SELECT Name FROM students WHERE students.CID2 IN (SELECT CID FROM courses);
4、联合查询mysql> (SELECT Name,Age FROM students) UNION (SELECT Tname,Age FROM tutors);
补充:
SELECT STATEMENT
MySQL Operator