一、SQL
- Structured Query Language:结构化查询语言,缩写为SQL
- 其实就是定义了操作所有关系型数据库的规则,标准组织指定的规则
- 每一种数据库操作的方式不一样的地方称之为"方言"
二、SQL通用语法
- SQL语句可以单行或者多行书写,以分号结尾
- 可以使用空格和缩进来增强语句的可读性
- MySQL数据库的SQL语句不区分大小写,但是关键字建议大写
- 注释方式
三、SQL的分类
- DDL(Data Definition Language):数据定义语言
操作数据库和表
- DML(Data Manipulation Language):数据库操作语言
增删改表中的数据
- DQL(Data Query Language):数据查询语言
查询表
DCL(Data Control Language):数据库控制语言
授权操作权限
DDL:操作数据库、表
1、操作数据库:CRUD
C(Create):创建
mysql> CREATE DATABASE city;
mysql> CREATE DATABASE IF NOT EXISTS TEST;
mysql> CREATE DATABASE TEXT CHARACTER SET GBK;
mysql> CREATE DATABASE IF NOT EXISTS SCHHOL CHARACTER SET GBK;
R(Retrieve):查询
SHOW DATABASES;
mysql> SHOW DATABASES;
+
| Database |
+
| city |
| information_schema |
| mysql |
| performance_schema |
| sys |
+
mysql> show create database mysql;
+
| Database | Create Database |
+
| mysql | CREATE DATABASE `mysql` |
+
U(Update):修改
mysql> ALTER DATABASE SCHOOL CHARACTER SET UTF8;
D(Delete):删除
mysql> DROP DATABASE SCHOOL;
mysql> DROP DATABASE IF EXISTS SCHOOL;
mysql> USE CITY;
mysql> SELECT DATABASE();
+
| DATABASE() |
+
| city |
+
1 row in set (0.00 sec)
2、操作表
C(Create):创建
CREATE TABLE 表名(
列名1,数据类型1,
列名2,数据类型2,
列名3,数据类型3
......
列名n,数据类型n
);
INT 整数
DOUBLE 小数(指定一共多少位,小数点后多少位):SCORE DOUBLE(5,2)
DATE 日期类型:只包含年月日,yyyy-MM-dd
DATETIME 时间类型:年月日时分秒,yyyy-MM-dd HH:mm:ss
TIMESTAMP 时间戳类型:年月日时分秒,yyyy-MM-dd HH:mm:ss
VARCHAR 字符串类型(指定长度):NAME VARCHAR(20)
mysql> CREATE TABLE STU_MESSAGE(
-> ID INT,
-> NAME VARCHAR(32),
-> AGE INT,
-> SCORE DOUBLE(4,1),
-> BIRTHDAY DATE,
-> INSERT_TIME TIMESTAMP
-> );
Query OK, 0 rows affected, 1 warning (0.60 sec)
mysql> DESC STU_MESSAGE;
+
| Field | Type | Null | Key | Default | Extra |
+
| ID | int(11) | YES | | NULL | |
| NAME | varchar(32) | YES | | NULL | |
| AGE | int(11) | YES | | NULL | |
| SCORE | double(4,1) | YES | | NULL | |
| BIRTHDAY | date | YES | | NULL | |
| INSERT_TIME | timestamp | YES | | NULL | |
+
6 rows in set (0.00 sec)
mysql> CREATE TABLE STU LIKE STU_MESSAGE;
R(Retrieve):查询
mysql> SHOW TABLES;
+
| Tables_in_city |
+
| student |
+
mysql> SHOW CREATE TABLE STUDENT;
+
| Table | Create Table |
+
| STUDENT | CREATE TABLE `student` (
`ID` int(11) DEFAULT NULL,
`NAME` varchar(32) DEFAULT NULL,
`AGE` int(11) DEFAULT NULL,
`SCORE` double(4,1) DEFAULT NULL,
`BIRTHDAY` date DEFAULT NULL,
`INSERT_TIME` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=gbk |
+
mysql> DESC USER;
+
| Field | Type | Null | Key | Default | Extra |
+
| Host | char(255) | NO | PRI | | |
| User | char(32) | NO | PRI | | |
| Select_priv | enum('N','Y') | NO | | N | |
| Insert_priv | enum('N','Y') | NO | | N | |
| Update_priv | enum('N','Y') | NO | | N | |
| Delete_priv | enum('N','Y') | NO | | N | |
| Create_priv | enum('N','Y') | NO | | N | |
| Drop_priv | enum('N','Y') | NO | | N | |
| Reload_priv | enum('N','Y') | NO | | N | |
| Shutdown_priv | enum('N','Y') | NO | | N | |
| Process_priv | enum('N','Y') | NO | | N | |
| File_priv | enum('N','Y') | NO | | N | |
| Grant_priv | enum('N','Y') | NO | | N | |
| References_priv | enum('N','Y') | NO | | N | |
| Index_priv | enum('N','Y') | NO | | N | |
| Alter_priv | enum('N','Y') | NO | | N | |
| Show_db_priv | enum('N','Y') | NO | | N | |
| Super_priv | enum('N','Y') | NO | | N | |
| Create_tmp_table_priv | enum('N','Y') | NO | | N | |
| Lock_tables_priv | enum('N','Y') | NO | | N | |
| Execute_priv | enum('N','Y') | NO | | N | |
| Repl_slave_priv | enum('N','Y') | NO | | N | |
| Repl_client_priv | enum('N','Y') | NO | | N | |
| Create_view_priv | enum('N','Y') | NO | | N | |
| Show_view_priv | enum('N','Y') | NO | | N | |
| Create_routine_priv | enum('N','Y') | NO | | N | |
| Alter_routine_priv | enum('N','Y') | NO | | N | |
| Create_user_priv | enum('N','Y') | NO | | N | |
| Event_priv | enum('N','Y') | NO | | N | |
| Trigger_priv | enum('N','Y') | NO | | N | |
| Create_tablespace_priv | enum('N','Y') | NO | | N | |
| ssl_type | enum('','ANY','X509','SPECIFIED') | NO | | | |
| ssl_cipher | blob | NO | | NULL | |
| x509_issuer | blob | NO | | NULL | |
| x509_subject | blob | NO | | NULL | |
| max_questions | int(11) unsigned | NO | | 0 | |
| max_updates | int(11) unsigned | NO | | 0 | |
| max_connections | int(11) unsigned | NO | | 0 | |
| max_user_connections | int(11) unsigned | NO | | 0 | |
| plugin | char(64) | NO | | caching_sha2_password | |
| authentication_string | text | YES | | NULL | |
| password_expired | enum('N','Y') | NO | | N | |
| password_last_changed | timestamp | YES | | NULL | |
| password_lifetime | smallint(5) unsigned | YES | | NULL | |
| account_locked | enum('N','Y') | NO | | N | |
| Create_role_priv | enum('N','Y') | NO | | N | |
| Drop_role_priv | enum('N','Y') | NO | | N | |
| Password_reuse_history | smallint(5) unsigned | YES | | NULL | |
| Password_reuse_time | smallint(5) unsigned | YES | | NULL | |
| Password_require_current | enum('N','Y') | YES | | NULL | |
| User_attributes | json | YES | | NULL | |
+
U(Update):修改
mysql> ALTER TABLE STU RENAME TO STUDENT;
mysql> ALTER TABLE STUDENT CHARACTER SET UTF8;
mysql> ALTER TABLE STUDENT ADD GENDER VARCHAR(10);
mysql> ALTER TABLE STUDENT DROP SEX;
mysql> ALTER TABLE STUDENT CHANGE GENDER SEX VARCHAR(20);
mysql> ALTER TABLE STUDENT MODIFY SEX VARCHAR(10);
D(Delete):删除
mysql> DROP TABLE IF EXISTS STUDENT;
DML:增删改表中数据
1、添加数据
INSERT INTO TABLE_NAME(NAME1,NAME2,...,NAMEn)VALUES (VALUE1,VALUE2,...,VALUEn);
1、列名和值要一一对应
2、如果表名后面不定义列名,则默认给所有列添加值
3、除了数字之外的其他类型需要双引号或者是单引号
INSERT INTO STUDENT(ID, NAME, AGE) VALUES (1, '张无忌', 18);
INSERT INTO student VALUES(2, '赵敏', 17, 99.9, '20000510', CURRENT_TIMESTAMP());
2、删除数据
DELETE FROM TABLE_NAME WHERE CONDITION;
1、如果不加条件,就是删除表中所有数据
2、如果要删除全部的数据,最好采用TRUNCATE,因为如果是采用DELETE,有多少的数据就会执行多少次,效率特别低
DELETE FROM STUDENT WHERE ID = 1;
TRUNCATE TABLE STUDENT;
3、修改数据
UPDATE TABLE_NAME SET NAME1 = VALUE1, NAME2 = VALUE2,..., NAMEn = VALUEn WHERE CONDITION;
1、如果不加任何条件,则将表中的全部数据进行修改
UPDATE STUDENT SET AGE = 117 WHERE NAME = '赵敏';
DQL:查询
SELECT
字段列表
FROM
表名列表
WHERE
条件列表
GROUP BY
分组字段
HAVING
分组之后的条件
ORDER BY
排序
LIMIT
分页限定
基础查询
1、多个字段查询
SELECT NAME1,NAME2,...,NAMEn FROM TABLE_NAME;
1、如果查询多个字段,可以使用‘*’来替换所有的NAME
SELECT NAME, AGE FROM STUDENT;
SELECT * FROM STUDENT;
2、去除重复
SELECT DISTINCT * FROM TABLE_NAME;
1、必须是结果一模一样才会判断为重复数据
SELECT DISTINCT ADDRESS FROM STUDENT;
3、计算列
SELECT NAME1,NAME2,...NAMEn,NAMEi 'OPERATOR' NAMEj FROM TABLE_NAME;
OPERATOR:表示一般的四则运算符号,并且NAMEi和NAMEj为数值
1、IFNULL('EXPRESSION1','EXPRESSION2')
EXPRESSION1:表示需要判断的字段
EXPRESSION2:EXPRESSION1字段为NULL的时候将会使用其进行替换
SELECT NAME, ENGLISH, MATH, MATH + ENGLISH FROM STUDENT;
SELECT NAME, ENGLISH, MATH, MATH + IFNULL(ENGLISH, 0) FROM STUDENT;
4、起别名
SELECT NAME AS name FROM TBALE_NAME;
1、AS也可以省略
SELECT NAME, ENGLISH, MATH, MATH + IFNULL(ENGLISH, 0) AS all_score FROM STUDENT;
SELECT NAME, ENGLISH AS 英语, MATH AS 数学, MATH + IFNULL(ENGLISH, 0) AS 总分 FROM STUDENT;
条件查询
>, <, <=, >=, =, <>
BETWEEN...AND
IN(set)
LIKE:模糊查询
IS NULL
and(&&),or(||),not(!)
1、精确条件查询
SELECT * FROM WHERE CONDITION;
SELECT * FROM STUDENT WHERE AGE > 20;
SELECT * FROM student WHERE age = 20;
SELECT * FROM student WHERE age != 20;
SELECT * FROM student WHERE age <> 20;
SELECT * FROM STUDENT WHERE AGE BETWEEN 20 AND 30;
SELECT * FROM STUDENT WHERE AGE >= 20 && AGE <= 30;
SELECT * FROM STUDENT WHERE AGE >= 20 AND AGE <= 30;
SELECT * FROM STUDENT WHERE AGE = 22 OR AGE = 18 OR AGE = 25;
SELECT * FROM STUDENT WHERE AGE IN(22, 18, 25);
SELECT * FROM student WHERE english IS NULL;
SELECT * FROM student WHERE english IS NOT NULL;
2、模糊条件查询
SELECT * FROM STUDENT WHERE NAME LIKE 'EXPRESSION';
占位符:
1、'_':单个任意字符
2、'%':零或多个任意字符
SELECT * FROM student WHERE NAME LIKE '马%';
SELECT * FROM student WHERE NAME LIKE '_化%';
SELECT * FROM student WHERE NAME LIKE '___';
SELECT * FROM student WHERE NAME LIKE '%马%';
排序查询
SELECT * FROM TABLE_NAME ORDER BY 'NAME1' 'SORT_WAY1','NAME2' 'SORT_WAY2',...,'NAMEn' 'SORT_WAYn';
1、ASC:升序排列,并且是默认排序
2、DESC:降序排列
3、多个排序条件时,当前面的条件一样时,才会判断后面的条件
SELECT * FROM student ORDER BY math DESC;
SELECT * FROM student ORDER BY math ASC, english ASC;
聚合函数
- 含义:将一列数据作为一个整体,进行纵向的计算
- 主要的聚合函数:
COUNT():计算个数,会排除NULL值,使用IFNULL()或者是使用只包含非空的列
max():计算最大值
min():计算最小值
sum():求和
AVG():计算平均值
SELECT COUNT(NAME) FROM STUDENT;
SELECT COUNT(IFNULL(english, 0)) FROM STUDENT;
SELECT MAX(math) FROM student;
SELECT MIN(math) FROM student;
SELECT SUM(math) FROM student;
SELECT SUM(IFNULL(english, 0)) FROM student;
SELECT AVG(math) FROM student;
分组查询
SELECT * FROM STUDENT GROUP BY NAME1,...NAMEn;
1、分组之后查询的字段:要么是分组字段,要么是聚合函数
2、WHERE和HAVING的区别:
WHERE:
在分组之前进行限定,是是否参与分组的条件;
后面不可以跟聚合函数的判断;
HAVING:
在分组之后进行限定,是分组之后是否进行查询的条件;
后面可以跟聚合函数的判断;
SELECT sex,AVG(math) FROM student GROUP BY sex;
SELECT sex,AVG(math) AS average FROM student GROUP BY sex ORDER BY average DESC;
SELECT sex, AVG(math) FROM student WHERE math >= 70 GROUP BY sex;
SELECT sex, AVG(math), COUNT(id) AS SUM FROM student WHERE math >= 70 GROUP BY sex HAVING SUM > 2;
分页查询
SELECT * FROM STUDENT LIMIT START_INDEX,MESSAGE_SUM;
'START_INDEX':开始的索引
'MESSAGE_SUM':每页查询的条数
1、START_INDEX= (n-1)*MESSAGE_SUM;(n为页数)
2、分页操作是一个方言
SELECT * FROM student LIMIT 0,3;
SELECT * FROM student LIMIT 3,3;
四、约束
- 概念:对表中的数据进行限定,从而保证数据的正确性、有效性、完整性
- 分类:
1、主键约束:PRIMARY KEY
2、非空约束:NOT NULL
3、唯一约束:UNIQUE
4、外键约束:FOREIGN KEY
1、创建表时添加约束
CREATE TABLE stu (
id INT,
NAME VARCHAR(20) NOT NULL
);
2、创建完毕后,添加约束
ALTER TABLE stu MODIFY NAME VARCHAR(20) NOT NULL;
1、主键约束
1、含义:非空且唯一
2、一张表只能有一个字段是主键
3、主键就是一张表中记录的唯一标识,类似身份证号
CREATE TABLE stu (
id INT PRIMARY KEY,
NAME VARCHAR(20)
);
CREATE TABLE stu (
id INT PRIMARY KEY AUTO_INCREMENT,
NAME VARCHAR(20)
);
ALTER TABLE stu MODIFY id INT PRIMARY KEY;
ALTER TABLE stu MODIFY id INT AUTO_INCREMENT;
ALTER TABLE stu DROP PRIMARY KEY;
ALTER TABLE stu MODIFY id INT;
2、非空约束
CREATE TABLE stu (
id INT,
NAME VARCHAR(20) NOT NULL
);
ALTER TABLE stu CHANGE NAME NAME VARCHAR(20);
ALTER TABLE stu MODIFY NAME VARCHAR(20);
ALTER TABLE stu MODIFY NAME VARCHAR(20) NOT NULL;
CREATE TABLE stu (
id INT PRIMARY KEY AUTO_INCREMENT,
NAME VARCHAR(20)
);
3、唯一约束
CREATE TABLE stu (
id INT,
phone_numb VARCHAR(20) UNIQUE
);
ALTER TABLE stu MODIFY phone_numb VARCHAR(20) UNIQUE;
ALTER TABLE stu DROP INDEX phone_number;
4、外键约束
- 概念:让表之间产生关系,从而保证数据的正确性
- 创建实例SQL语句
CREATE TABLE department (
id INT PRIMARY KEY AUTO_INCREMENT,
dep_name VARCHAR(30),
dep_location VARCHAR(30)
);
CREATE TABLE employee (
id INT PRIMARY KEY AUTO_INCREMENT,
NAME VARCHAR(20),
age INT,
dep_id INT
);
INSERT INTO department VALUES (NULL, '研发部', '广州'),
(NULL, '销售部', '深圳');
INSERT INTO employee (NAME, age, dep_id) VALUES ('张三', 20, 1),
('李四', 21, 1),
('王五', 20, 1),
('老王', 20, 2),
('大王', 22, 2),
('小王', 18, 2);
CREATE TABLE table_name (
name1 typedef1,
name2 typedef2,
...,
namen typedefn,
CONSTRAINT 外键名称 FOREIGN KEY (外键约束的列名) REFERENCES 主表名称(主表的主键名称)
);
CREATE TABLE department (
id INT PRIMARY KEY AUTO_INCREMENT,
dep_name VARCHAR(30),
dep_location VARCHAR(30)
);
CREATE TABLE employee (
id INT PRIMARY KEY AUTO_INCREMENT,
NAME VARCHAR(20),
age INT,
dep_id INT,
CONSTRAINT emp_dep_id FOREIGN KEY (dep_id) REFERENCES department(id)
);
ALTER TABLE employee DROP FOREIGN KEY emp_dep_id;
ALTER TABLE employee ADD CONSTRAINT emp_dep_id FOREIGN KEY (dep_id) REFERENCES department(id);
ALTER TABLE employee ADD CONSTRAINT emp_dep_id FOREIGN KEY (dep_id) REFERENCES department(id) ON UPDATE CASCADE;
ALTER TABLE employee ADD CONSTRAINT emp_dep_id FOREIGN KEY (dep_id) REFERENCES department(id) ON DELETE CASCADE;