SQL语句

一、SQL语句的语义

DDL: 数据定义语言
DCL: 数据控制语言
DML: 数据操作语言
DQL: 数据查询语言

二、DDL语句 数据定义语言 (CREATE)

1.CREATE针对库的操作

1)查看语法

mysql> help create database;
Name: 'CREATE DATABASE'
Description:
Syntax:
CREATE {DATABASE | SCHEMA} [IF NOT EXISTS] db_name
    [create_specification] ...

create_specification:
    [DEFAULT] CHARACTER SET [=] charset_name
  | [DEFAULT] COLLATE [=] collation_name

2)创建库

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

mysql> create schema lhd2;
Query OK, 1 row affected (0.00 sec)

3)创建库时忽略已存在报错 [IF NOT EXISTS]

mysql> create schema lhd;
ERROR 1007 (HY000): Can't create database 'lhd'; database exists

mysql> create schema if not exists lhd;
Query OK, 1 row affected, 1 warning (0.00 sec)

mysql> create schema if not exists lhd;
Query OK, 1 row affected, 1 warning (0.00 sec)

4)查看数据库创建

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

5)指定字符集和校验规则创建数据库

mysql> create database qiudao charset utf8 collate utf8_general_ci;
Query OK, 1 row affected (0.00 sec)

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

6)删除数据库

mysql> drop database qiudao;

7)修改数据库

mysql> alter database qiudao charset utf8mb4 collate utf8mb4_general_ci;
Query OK, 1 row affected (0.00 sec)

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

2.CREATE针对表的操作

1)查看语法

mysql> help create table;

2)建表

#1.先进入数据库
mysql> use qiudao;
Database changed

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

#2.创建表,最少有一列
mysql> create table qiudao;
ERROR 1113 (42000): A table must have at least 1 column

mysql> create table qiudao(id int);
Query OK, 0 rows affected (0.02 sec)

#3.查看表
mysql> show tables;
+------------------+
| Tables_in_qiudao |
+------------------+
| qiudao           |
+------------------+
1 row in set (0.00 sec)

3)数据类型

int:            整数  -2^31 ~ 2^31-1    (-2147483648 ~ 2147483647)
tinyint:        最小整数  -128 ~ 127
varchar:        字符类型(变长)
char:            字符类型(定长)
enum:            枚举类型  指定多个选项,选一个选项填写,不允许填写选项以外的值
datetime:        时间类型

4)建表题:

表名:student
sid
sname
sage
sgender
scometime

#1.建表
mysql> create table student(
    -> sid int,
    -> sname varchar(10),
    -> sage tinyint,
    -> sgender enum('man','woman'),
    -> scometime datetime);
Query OK, 0 rows affected (0.03 sec)

#2.插入数据
mysql> insert into student values(1,'邱导','-10','woman',now());

#3.查看数据
mysql> select * from student;
+------+--------+------+---------+---------------------+
| sid  | sname  | sage | sgender | scometime           |
+------+--------+------+---------+---------------------+
|    1 | 邱导   |  -10 | woman   | 2020-04-17 09:38:46 |
+------+--------+------+---------+---------------------+
1 row in set (0.00 sec)

5)建表数据属性

not null:         非空
primary key:     主键(唯一且非空的)
auto_increment: 自增(此列必须是:primary key或者unique key)
unique key:     单独的唯一的
default:         默认值
unsigned:         无符号,非负数        #添加unsigned属性,会加到数据属性中,所以把这个属性写到数据属性后面
comment:         注释

primary key = unique key + not null

6)加上建表属性创建学生表

#1.创建表
create table student(
sid int unsigned not null primary key auto_increment comment '学号',
sname varchar(10) not null comment '学生姓名',
sage tinyint unsigned not null comment '学生年龄',
sgender enum('m','f') not null default 'm' comment '学生性别',
scometime datetime default now() comment '入学时间',
sbirthday datetime comment '学生生日',
sclass varchar(20) comment '学生班级');

#2.查看建表语句
mysql> show create table student;
| student | CREATE TABLE `student` (
  `sid` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '学号',
  `sname` varchar(10) NOT NULL COMMENT '学生姓名',
  `sage` tinyint(3) unsigned NOT NULL COMMENT '学生年龄',
  `sgender` enum('m','f') NOT NULL DEFAULT 'm' COMMENT '学生性别',
  `scometime` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '入学时间',
  `sbirthday` datetime DEFAULT NULL COMMENT '学生生日',
  `sclass` varchar(20) DEFAULT NULL COMMENT '学生班级',
  PRIMARY KEY (`sid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4                           |
1 row in set (0.00 sec)

#3.插入语句
mysql> insert into student values(1,'邱导',88,'f',now(),now(),'初三1班');
Query OK, 1 row affected (0.00 sec)

mysql> insert into student values(2,'邱导',88,'f',NULL,NULL,'初三1班');
Query OK, 1 row affected (0.00 sec)

mysql> insert into student values('4','林',18,'m',NULL,NULL,'初四2班');
Query OK, 1 row affected (0.00 sec)

mysql> insert student(sname,sage) values('哈',18);

#4.查看语句
mysql> select * from student;
+-----+--------+------+---------+---------------------+---------------------+------------+
| sid | sname  | sage | sgender | scometime           | sbirthday           | sclass     |
+-----+--------+------+---------+---------------------+---------------------+------------+
|   1 | 邱导   |   88 | f       | 2020-04-17 10:28:19 | 2020-04-17 10:28:19 | 初三1班    |
|   2 | 邱导   |   88 | f       | NULL                | NULL                | 初三1班    |
|   3 | 邱     |   74 | m       | NULL                | NULL                | 初三1班    |
|   4 | 林     |   18 | m       | NULL                | NULL                | 初四2班    |
+-----+--------+------+---------+---------------------+---------------------+------------+
4 rows in set (0.00 sec)

7)删除表

mysql> drop table student;

8)修改表

#1.修改表名
mysql> alter table linux7 rename linux7qi;
                  原表名          新表名

#2.在最后添加列
mysql> alter table linux7qi add zy varchar(10);

#3.添加多个列
mysql> alter table linux7qi add qiudao varchar(10),add dongge varchar(10);

#4.添加列到表前面
mysql> alter table linux7qi add xiaohong varchar(10) first;

#5.指定位置添加列
mysql> alter table linux7qi add wupeng varchar(10) after zy;

#6.删除指定列
mysql> alter table linux7qi drop gcc;

#7.修改列的数据类型
mysql> alter table linux7qi modify zy int;

#8.修改列及属性
mysql> alter table linux7qi change dongge gcc int;

三、DCL语句 数据控制语言(GRANT,REVOKE)

1.GRANT 授权

#1.授权语句
mysql> grant all on *.* to root@'%' identified by '123';

#2.查看用户权限
mysql> select * from mysql.user\G
mysql> show grants for root@'%';

max_queries_per_hour:一个用户每小时可发出的查询数量
mysql> grant all on *.* to test@'localhost' identified by '123' with max_queries_per_hour 2;
Query OK, 0 rows affected (0.00 sec)

max_updates_per_hour:一个用户每小时可发出的更新数量

max_connections_per_hour:一个用户每小时可连接到服务器的次数
mysql> grant all on *.* to test1@'localhost' identified by '123' with max_connections_per_hour 1;
Query OK, 0 rows affected (0.00 sec)

max_user_connections:允许同时连接数量
mysql> grant all on *.* to test2@'localhost' identified by '123' with max_user_connections 1;
Query OK, 0 rows affected (0.00 sec)

2.回收权限 revoke

#1.回收权限
mysql> revoke drop on *.* from root@'%';
Query OK, 0 rows affected (0.00 sec)

#2.查看权限,可以知道所有的权限都包含什么
mysql> show grants for root@'%';

#3.所有权限
SELECT, INSERT, UPDATE, DELETE, CREATE, RELOAD, SHUTDOWN, PROCESS, FILE, REFERENCES, INDEX, ALTER, SHOW DATABASES, SUPER, CREATE TEMPORARY TABLES, LOCK TABLES, EXECUTE, REPLICATION SLAVE, REPLICATION CLIENT, CREATE VIEW, SHOW VIEW, CREATE ROUTINE, ALTER ROUTINE, CREATE USER, EVENT, TRIGGER, CREATE, DROP

3.授权一个超级管理员

mysql> grant all on *.* to lhd@'%' identified by '123' with grant option;
Query OK, 0 rows affected (0.00 sec)

四、DML 数据操作语言 (INSERT,DELETE,UPDATE)

1.INSERT命令

#1.插入数据之前,一定先看表结构和建表规则
mysql> desc student;
mysql> show create table student;

#2.插入数据(不规范的写法)
mysql> insert into student values(6,'林',18,'m',NULL,NULL,NULL);

#3.插入一条数据(规范写法)
mysql> insert student(sname,sage) values('达',18);
mysql> insert student(sname,sage,sgender) values('丽',18,'f');

#4.插入多条数据(规范写法)
mysql> insert student(sname,sage,sgender) values('丽',18,'f'),('艺',18,'f'),('张音',18,'f');

2.update命令

#1.修改数据之前一点先查看数据
mysql> select * from student;
mysql> select * from qiudao.student;

#2.修改数据,错误的方法,这样会将整列都修改
mysql> update student set sgender'm';

#3.使用update一定要加where条件
mysql> update qiudao.student set sgender='f' where sid=11;
mysql> update qiudao.student set sgender='m' where sname='邱导' and sage='88';  #没有主键指点多个值

#4.如果要求整列修改
mysql> update student set sgender'm' where 1=1;

3.delete命令

#1.删除数据之前一点先查看数据
mysql> select * from student;
mysql> select * from qiudao.student;

#2.删除数据,错误的方法,会清空整个表
mysql> delete from qiudao.student;

#3.使用delete一定要加where条件
mysql> delete from qiudao.student where sid=1;
mysql> delete from qiudao.student where sname='林' and sage='18';

#4.清空表
truncate table student;

4.使用update代替delete

1)添加一列状态列

mysql> alter table student add status enum('1','0') default 1;

2)使用update修改数据状态

mysql> update student set status='0' where id=14;

3)查询有效的数据

mysql> select * from student where status=1;

五、DQL 数据查询语言(SELECT,desc)

1.select 查询数据

#1.查看表中所有数据,如果数据量太大,会导致内存撑爆
mysql> select * from qiudao.student;

#2.查询之前先查看下数据量
mysql> select count(*) from qiudao.student;

#3.查看指定列的数据
mysql> select user,host from mysql.user;

#4.按条件查询
mysql> select sname,sage from qiudao.student where sage=18;
mysql> select sname,sage from qiudao.student where sage=18 and sgender='f';

2.查询数据测试

#1.导入数据
mysql> \. /tmp/world.sql
或
mysql> source /tmp/world.sql

#2.查看表
mysql> use world
Database changed
mysql> show tables;
+-----------------+
| Tables_in_world |
+-----------------+
| city            |
| country         |
| countrylanguage |
+-----------------+
3 rows in set (0.00 sec)

#3.查看city表结构
mysql> desc city;

#4.查询city表数据
mysql> select * from city;

#5.查询指定列数据
mysql> select name,population from city;

#6.按照人口数量排序
#升序
mysql> select name,population from city order by population;
#降序
mysql> select name,population from city order by population desc;

#7.只看前十条
mysql> select name,population from city limit 10;
mysql> select name,population from city order by population limit 10;

#8.按照步长查询数据
mysql> select id,name,population from city limit 10,10;
#前面的10代表开始,后面的10代表再次展示个数称为步长
#商品也翻页原理:
mysql> select id,name,population from city limit 0,60;
mysql> select id,name,population from city limit 60,60;
mysql> select id,name,population from city limit 120,60;

3.按条件查询

#1.条件查询where可以接的符号
where接条件符号:= < > >= <= != <>
where接条件:or and like
= : 精确查询
< > >= <= != <> : 范围查询
like : 模糊查询

#2.查询中国城市人口
mysql> select name,population from city where CountryCode='CHN';

#3.查询黑龙江省的人口
mysql> select name,population from city where District='heilongjiang';

#4.查询中国人口数量小于100000的城市
mysql> select name,population from city where population < 100000 and countrycode='CHN';

#5.模糊查询
#国家代码以H结尾的
mysql> select * from city where countrycode like '%H';
#国家代码以H开头的
mysql> select * from city where countrycode like 'H%';
#国家代码包含H的
mysql> select * from city where countrycode like '%H%';

#6.查询中国或美国的城市人口 or in
mysql> select * from city where countrycode='CHN' or countrycode='USA';
mysql> select * from city where countrycode in ('CHN','USA');
#排除
mysql> select * from city where countrycode != 'CHN' and countrycode != 'USA';
mysql> select * from city where countrycode not in ('CHN','USA');

#7.联合查询 union all
mysql> select * from city where countrycode='CHN' union all select * from city where countrycode='USA';
Copyright © 高程程 all right reserved,powered by Gitbook修订于: 2021-05-18 21:14:41

results matching ""

    No results matching ""