一、数据库操作
(1)查看当前系统上已有的数据库:mysql> SHOW DATABASES;
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| performance_schema |
| test |
+--------------------+
4 rows in set (0.00 sec)
mysql>
(2)新建数据库:mysql> CREATE DATABASE test;
ERROR 1007 (HY000): Can't create database 'test'; database exists
mysql>
在创建数据库时,如果这个数据库存在,那么系统会报错;
假使我们将这个语句写到脚本中,那么我脚本将会终止执行,为了避免这样的事情,可以事先进行判断该数据看是否存在
例如:mysql> CREATE DATABASE IF NOT EXISTS test;
Query OK, 1 row affected, 1 warning (0.00 sec)
mysql>
加入判断(IF NOT EXISTS)这样就忽略掉了提示也就不会中断脚本的执行
,但是我们可以看到有一个警告:mysql> SHOW WARNINGS;
+-------+------+-----------------------------------------------+
| Level | Code | Message |
+-------+------+-----------------------------------------------+
| Note | 1007 | Can't create database 'test'; database exists |
+-------+------+-----------------------------------------------+
1 row in set (0.00 sec)
mysql>
例如:
mysql> CREATE DATABASE mydb;
Query OK, 1 row affected (0.00 sec)
mysql> SHOW DATABASES;;
+--------------------+
| Database |
+--------------------+
| information_schema |
| mydb |
| mysql |
| performance_schema |
| test |
+--------------------+
5 rows in set (0.00 sec)
ERROR:
No query specified
mysql>
2.删除数据库
在删除前判断这个数据库是否存在,存在的话执行才成功,如果在脚本中那么一样会被中断执行
mysql> DROP DATABASE testdb;
ERROR 1008 (HY000): Can't drop database 'testdb'; database doesn't exist
所以还是需要事先判断:mysql> DROP DATABASE IF EXISTS testdb;
Query OK, 0 rows affected, 1 warning (0.00 sec)
mysql> SHOW WARNINGS;
+-------+------+------------------------------------------------------+
| Level | Code | Message |
+-------+------+------------------------------------------------------+
| Note | 1008 | Can't drop database 'testdb'; database doesn't exist |
+-------+------+------------------------------------------------------+
1 row in set (0.00 sec)
mysql>
3.设定字符集或者排序规则
在我们把一个数据库从一个低版本升级到一个高版本以后,有时有需要手动的将有些特定库的数据字典升级
具体用法如下:ALTER {DATABASE | SCHEMA} [db_name]
alter_specification ...
ALTER {DATABASE | SCHEMA} db_name
UPGRADE DATA DIRECTORY NAME
alter_specification:
[DEFAULT] CHARACTER SET [=] charset_name
| [DEFAULT] COLLATE [=] collation_name
4.修改数据名
唯一做法:将数据库备份后,删除库,待新建好后导入表
5.创建表:CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name
(create_definition,......)
[table_options]
(create_definition,......)字段的定义:字段名、类型和类型修饰符
键、约束或索引PRIMARY KEY, UNIQUE KEY, FROEIGN KEY, CHECK
{INDEX|KEY}
[table_options]
ENGINE [=] engine_name
AUTO_INCREMENT [=] value
[DEFAULT]
COMMONT [=]
DELAY_KEY_WRITE [=] {0 | 1} 对提高性能有所帮助
INDEX_DIRECTORY [=] 'PATH' 索引位置
DATA DIRECTORY [=] 'PATH'
ROW_FORMAT
表创建第二种方式: 基于某张表创建一张表,复制表数据CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name
(create_definition,......)
[table_options]
select_statement
表创建第三种方式: 基于某张表创建一张表,复制表结构CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name
{LIKE old_tbl_name | (LIKE old_tbl_name)}
6.删除表:DROP [TEMPORARY] TABLE [IF EXTSTS]
tbl_name [,tbl_name...]
7.表修改:ALTER TABLE tbl_name
[alter_specification [, alter_specification]...]
修改字段定义:
插入新字段
删除字段 ALTER TABLE tb_name DROP col_name
修改字段
修改字段名称
修改字段类型及属性等
MODIFY
修改约束、键或索引:
8.表改名:mysql>RENAME TABLE old_tbl_name TO new_tbl_name
9.表插入(3种方式)1.{INSERT|REPLACE} INTO tb_name [(col1, col2,....)] {VAULES|VALUE}(val, val2,...) [,(val21, val22,....),.....]
2.{INSERT|REPLACE} INTO tb_naem SET col1=val1, clo2=val2,.....
3.INSERT INTO tb_name SELECT clause
REPLACE的工作机制:与INSERT相同,除了在新插入的数据与表中的主键或者惟一键索引定义的数据相同会替换老的行
10.表更新UPDATE [LOW_PRIORITY] [IGNORE] table_reference
SET col_name1=val1 [, col_name2=val2] ...
[WHERE where_condition]
[ORDER BY ...]
[LIMIT row_count]
通常情况下,必须要使用WHERE字句,或者使用LIMIT限制要修改的行数
11.表中字段删除:--safe-updates
DELETE [LOW_PRIORITY] [QUICK] [IGNORE] FROM tbl_name
[WHERE where_condition]
[ORDER BY ...]
[LIMIT row_count]
如果目的是清空整张表,则可使用mysql>TUNCATE tb_name
或者是将表结构复制出来后DROP掉表
二、表结构:
对于MyISAM,每个表有三个文件
tb_name.frm:表结构定义
tb_name.MYD:数据文件
tb_name.MYI:索引文件
对于InnoDB表,有两种存储方式
1.innodb_file_per_table=OFF
默认:每表有一个独立文件和一个多表共享的文件
tb_name.frm:表结构定义,位于数据库目录中
ibdata#:共享的表空间,默认位于数据目录(datadir指向)
2.innodb_file_per_table=ON
独立的表空间:
每个表在数据库目录下存储两个文件
tb_name.frm:每表有一个表结构文件
tb_name.ibd:一个独有的表空间
开启独立的表空间功能:
配置文件/etc/my.cnf中[mysqld]字段中添加:innodb_file_per_table=ON(建议安装完mysql后添加此项)
三、表查询操作:
单表查询:
多表查询:
选择和投影
选择:挑选符合条件的行
投影:挑选要现实的字段
投影:SELECT 字段1, 字段2, ......FROM tb_name;
SELECT * FROM tb_name;
选择:SELECT 字段1,......FROM tb_name WHERE 子句;
布尔条件表达式
布尔条件表达式操作符:
IS NOLL
mysql>SELECT * FROM tb_name WHERE 字段 IS NOLL;
IS NOT NULL
字符串比较
LIKE {% | _ } 支持通配符
%:任意长度的任意字符
_ :任意单个字符
RLIKE,REGEXP 支持使用正则表达式()
IN :用于判断指定字段的值是否在给定的列表中;
BETWEEN....AND.... :用于判断指定的字段的值表示在某个字段值之间
A>=20 AND X<40
X BETWEEN 20 AND 40
组合条件测试:
NOT, !
AND, &&
OR, ||
ORDER BY ..(默认升序)
ASC 升序
DESC 降序
聚合函数:
SUM( ), 求和
AVG( ), 平均值
MAX( ), 最大值
MIN( ), 最小值
COUNT( ), 统计
mysql>SELECT XXX(字段) FROM tb_name [WHERE 子句]
分组:
GROUP BY
对GROUP BY过滤的子句
HAVING
LIMIT N[,M]
N:指定哪行
M:偏移
SELECT语句的执行流程:
FROM Clause --> WHERE clause -->GROUP BY -->HAVING clause --> ORDER BY ... --> SELECT --> LIMIT -->END
SELECT常用结合使用方式
SELECT ...
SELECT ... FROM ... ORDER BY ...
SELECT ... FROM ... GROUP BY ... HAVING ...
SELECT ... FROM ... WHERE ...
SELECT ... FROM ... WHERE ... GROUP BY ... LIMIT
SELECT ... FROM ... HAVING
SELECT 常用修饰符:
DISTINCT: 指定的结果想通过的只显示一次;
SQL_CACHE: 明确说明需要将执行结果缓存于查询缓存中;
SQL_NO_CACHE: 明确说明不需要将执行结果缓存于查询缓存中;
MySQL多表查询和子查询:
交叉联结(笛卡尔乘积) 避免使用
内联结(Inner Jion):通过匹配两个表之间的等值关系,建立的联结
例如:SELECT * FROM student,cources WHERE students.CID1=cources.CID;
外联结(Outer Jion)两个表之间不是等值关系,一个表中可能没有值。
左外SELECT...FROM...LEFT JION...ON...
以左表为基准,右表没有就显示为空。 (不需要where)
例如:SELECT name,cname FROM student LEFT JION courses ON student.CID1=courses.CID
右外SELECT...FROM...RIGHT JION...ON... 以右表为基准,左表可能为空。(不需要where)
完全外
自联结 (SELF JION):同一个表的两个字段建立联系。
例如:SELECT s1.name,s2.name FROM students AS s1,students AS s2 WHERE s1.TID=s2.SID
联合(UNION):将两个字段的查询结果联结在一起(也就是将两个查询语句用UNION联合起来)
子查询:在查询中嵌套的查询
用于Where中的子查询1.用于比较表达式中的子查询
子查询的返回值只能有一个
2.用于EXISTS中的子查询
判断存在与否,可以返回多个值
3.用于IN中的子查询
判断存在指定列表中,可以返回多个值
用于FROM中的子查询:SELECT alias.col,....from (SELECT clause) AS alias WHERE condition
MySQL的联合查询:
把两个或多个查询语句的结果合并成一个结果进行输出:
SELECT clauase UNBION SELECT clauase UNION ...
在整个查询语句前面使用"EXPLAIN"显示语句执行过程
查询表的索引
mysql>SHOW INDEXES FROM tb_name
MySQL视图
创建视图:CREATE VIEW view_name AS select_statemen; select_statement表示SELECT语句,将SELECT语句查询得到的表建立为一个视图。
删除视图:DROP VIEW view_name
显示创建view的命令:SHOW CREATE VIEW view_name
虚表中插入数据时查看基表是否允许,但mysql中不允许向视图中插入数据。
对视图的查询就是一种子查询,在实际操作中应避免子查询。
练习题:新建如下表(包括结构和内容):ID Name Age Gender Course
1 Ling Huchong 24 Male Hamogong
2 Huang Rong 19 Female Chilian Shenzhang
3 Lu Wushaung 18 Female Jiuyang Shenggong
4 Zhu Ziliu 52 Male Pixie Jianfa
5 Chen Jialuo 22 Male Xianglong Shiba Zhang
6 Ou Yangfeng 70 Male Shenxiang Bannuo Gong
操作步骤:#创建库
mysql> CREATE DATABASE mydb
Query OK, 1 row affected (0.00 sec)
mysql> USE mydb
Database changed
#创建表
mysql> CREATE TABLE students (
-> ID INT AUTO_INCREMENT UNIQUE KEY,
-> Name CHAR(30),
-> Age TINYINT UNSIGNED NOT NULL,
-> GENDER ENUM('Male','Female') NOT NULL,
-> Corse VARCHAR(50) NOT NULL);
Query OK, 0 rows affected (0.02 sec)
#查看表
mysql> SHOW TABLES ;
+----------------+
| Tables_in_mydb |
+----------------+
| students |
+----------------+
1 row in set (0.00 sec)
#查看表结构
mysql> DESC students;
+--------+-----------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------+-----------------------+------+-----+---------+----------------+
| ID | int(11) | NO | PRI | NULL | auto_increment |
| Name | char(30) | YES | | NULL | |
| Age | tinyint(3) unsigned | NO | | NULL | |
| GENDER | enum('Male','Female') | NO | | NULL | |
| Corse | varchar(50) | NO | | NULL | |
+--------+-----------------------+------+-----+---------+----------------+
5 rows in set (0.00 sec)
#添加表内容
mysql> INSERT INTO students (ID,Name,Age,Gender,Course) VALUES
-> (1,'Ling Huchong',24,'Male','Hamogong'),
-> (2,'Huang Rong',19,'Female','Chilian Shenzhang'),
-> (3,'Lu Wushaung',18,'Female','Jiuyang Shenggong'),
-> (4,'Zhu Ziliu',52,'Male','Pixie Jianfa'),
-> (5,'Chen Jialuo',22,'Male','Xianglong Shiba Zhang'),
-> (6,'Ou Yangfeng',70,'Male','Shenxiang Bannuo Gong');
Query OK, 6 rows affected (0.01 sec)
Records: 6 Duplicates: 0 Warnings: 0
#查看表内容:
mysql> SELECT * FROM students;
+----+--------------+-----+--------+-----------------------+
| ID | Name | Age | GENDER | Course |
+----+--------------+-----+--------+-----------------------+
| 1 | Ling Huchong | 24 | Male | Hamogong |
| 2 | Huang Rong | 19 | Female | Chilian Shenzhang |
| 3 | Lu Wushaung | 18 | Female | Jiuyang Shenggong |
| 4 | Zhu Ziliu | 52 | Male | Pixie Jianfa |
| 5 | Chen Jialuo | 22 | Male | Xianglong Shiba Zhang |
| 6 | Ou Yangfeng | 70 | Male | Shenxiang Bannuo Gong |
+----+--------------+-----+--------+-----------------------+
6 rows in set (0.00 sec)
mysql>
1、新增字段:
Class 字段定义自行选择;放置于Name字段后;mysql> ALTER TABLE students ADD Class INT NULL AFTER Name;
Query OK, 6 rows affected (0.02 sec)
Records: 6 Duplicates: 0 Warnings: 0
mysql> SELECT * FROM students;
+----+--------------+-------+-----+--------+-----------------------+
| ID | Name | Class | Age | GENDER | Course |
+----+--------------+-------+-----+--------+-----------------------+
| 1 | Ling Huchong | NULL | 24 | Male | Hamogong |
| 2 | Huang Rong | NULL | 19 | Female | Chilian Shenzhang |
| 3 | Lu Wushaung | NULL | 18 | Female | Jiuyang Shenggong |
| 4 | Zhu Ziliu | NULL | 52 | Male | Pixie Jianfa |
| 5 | Chen Jialuo | NULL | 22 | Male | Xianglong Shiba Zhang |
| 6 | Ou Yangfeng | NULL | 70 | Male | Shenxiang Bannuo Gong |
+----+--------------+-------+-----+--------+-----------------------+
6 rows in set (0.00 sec)
mysql>
2、将ID字段名称修改为TID;mysql> ALTER TABLE students CHANGE ID TID INT AUTO_INCREMENT UNIQUE KEY;
Query OK, 6 rows affected (0.02 sec)
Records: 6 Duplicates: 0 Warnings: 0
mysql> SELECT * FROM students;
+-----+--------------+-------+--------+-----------------------+-----+
| TID | Name | Class | GENDER | Course | Age |
+-----+--------------+-------+--------+-----------------------+-----+
| 1 | Ling Huchong | NULL | Male | Hamogong | 24 |
| 2 | Huang Rong | NULL | Female | Chilian Shenzhang | 19 |
| 3 | Lu Wushaung | NULL | Female | Jiuyang Shenggong | 18 |
| 4 | Zhu Ziliu | NULL | Male | Pixie Jianfa | 52 |
| 5 | Chen Jialuo | NULL | Male | Xianglong Shiba Zhang | 22 |
| 6 | Ou Yangfeng | NULL | Male | Shenxiang Bannuo Gong | 70 |
+-----+--------------+-------+--------+-----------------------+-----+
6 rows in set (0.00 sec)
mysql>
3、将Age字段放置最后;mysql> ALTER TABLE students MODIFY Age TINYINT UNSIGNED NOT NULL AFTER Course;
Query OK, 6 rows affected (0.02 sec)
Records: 6 Duplicates: 0 Warnings: 0
mysql> SELECT * FROM students;
+----+--------------+-------+--------+-----------------------+-----+
| ID | Name | Class | GENDER | Course | Age |
+----+--------------+-------+--------+-----------------------+-----+
| 1 | Ling Huchong | NULL | Male | Hamogong | 24 |
| 2 | Huang Rong | NULL | Female | Chilian Shenzhang | 19 |
| 3 | Lu Wushaung | NULL | Female | Jiuyang Shenggong | 18 |
| 4 | Zhu Ziliu | NULL | Male | Pixie Jianfa | 52 |
| 5 | Chen Jialuo | NULL | Male | Xianglong Shiba Zhang | 22 |
| 6 | Ou Yangfeng | NULL | Male | Shenxiang Bannuo Gong | 70 |
+----+--------------+-------+--------+-----------------------+-----+
6 rows in set (0.00 sec)
mysql>
练习二:以下操作在students表上执行mysql> select * from students;
+-------+---------------+-----+--------+---------+-----------+
| StuID | Name | Age | Gender | ClassID | TeacherID |
+-------+---------------+-----+--------+---------+-----------+
| 1 | Shi Zhongyu | 22 | M | 2 | 3 |
| 2 | Shi Potian | 22 | M | 1 | 7 |
| 3 | Xie Yanke | 53 | M | 2 | 16 |
| 4 | Ding Dian | 32 | M | 4 | 4 |
| 5 | Yu Yutong | 26 | M | 3 | 1 |
| 6 | Shi Qing | 46 | M | 5 | NULL |
| 7 | Xi Ren | 19 | F | 3 | NULL |
| 8 | Lin Daiyu | 17 | F | 7 | NULL |
| 9 | Ren Yingying | 20 | F | 6 | NULL |
| 10 | Yue Lingshan | 19 | F | 3 | NULL |
| 11 | Yuan Chengzhi | 23 | M | 6 | NULL |
| 12 | Wen Qingqing | 19 | F | 1 | NULL |
| 13 | Tian Boguang | 33 | M | 2 | NULL |
| 14 | Lu Wushuang | 17 | F | 3 | NULL |
| 15 | Duan Yu | 19 | M | 4 | NULL |
| 16 | Xu Zhu | 21 | M | 1 | NULL |
| 17 | Lin Chong | 25 | M | 4 | NULL |
| 18 | Hua Rong | 23 | M | 7 | NULL |
| 19 | Xue Baochai | 18 | F | 6 | NULL |
| 20 | Diao Chan | 19 | F | 7 | NULL |
| 21 | Huang Yueying | 22 | F | 6 | NULL |
| 22 | Xiao Qiao | 20 | F | 1 | NULL |
| 23 | Ma Chao | 23 | M | 4 | NULL |
| 24 | Xu Xian | 27 | M | NULL | NULL |
| 25 | Sun Dasheng | 100 | M | NULL | NULL |
+-------+---------------+-----+--------+---------+-----------+
25 rows in set (0.00 sec)
mysql>
1、以ClassID分组,显示每班的同学的人数,除了空组;
mysql> SELECT ClassID ,Count(Name) FROM students WHERE ClassID IS NOT NULL GROUP BY ClassID;
+---------+-------------+
| ClassID | Count(Name) |
+---------+-------------+
| 1 | 4 |
| 2 | 3 |
| 3 | 4 |
| 4 | 4 |
| 5 | 1 |
| 6 | 4 |
| 7 | 3 |
+---------+-------------+
7 rows in set (0.00 sec)
mysql>
2、以Gender分组,显示其年龄之和;mysql> SELECT Gender,SUM(Age) FROM students GROUP BY Gender;
+--------+----------+
| Gender | SUM(Age) |
+--------+----------+
| F | 190 |
| M | 495 |
+--------+----------+
2 rows in set (0.00 sec)
mysql>
3、以ClassID分组,显示其平均年龄大于25的班级,除了空组;
mysql> SELECT ClassID,AVG(Age) FROM students WHERE ClassID IS NOT NULL GROUP BY ClassID HAVING AVG(Age) >25;
+---------+----------+
| ClassID | AVG(Age) |
+---------+----------+
| 2 | 36.0000 |
| 5 | 46.0000 |
+---------+----------+
2 rows in set (0.00 sec)
mysql>
4、以Gender分组,显示各组中年龄大于25的学员的年龄之和;
mysql> SELECT Gender,SUM(Age) FROM students WHERE Age >25 GROUP BY Gender ;
+--------+----------+
| Gender | SUM(Age) |
+--------+----------+
| M | 317 |
+--------+----------+
1 row in set (0.00 sec)
mysql>