zoukankan      html  css  js  c++  java
  • sql 语句管理

    SQL语句

    一、sql语句的语义

    DDL:Data Definition Language              # 数据定义语言 (create、alter)
    DCL:Data Control Language	           # 数据控制语言 (grant、revoke、commit、rollback)
    DML:Data Manipulate	Language           # 数据操作语言 (insert、delete、update)
    DQL:Data Query Language		   # 数据查询语言 (select、desc)
    

    二、DDL --数据定义语言

    1. create 操作库

    1)查看语法

    mysql> help create database;
    Syntax:
    CREATE {DATABASE | SCHEMA} [IF NOT EXISTS] db_name [create_specification] ...
    
    create_specification:
        [DEFAULT] CHARACTER SET [=] charset_name | [DEFAULT] COLLATE [=] collation_name
    

    2)创建库

    #1.建库
    mysql> create database db01;
    Query OK, 1 row affected (0.00 sec)
    
    #2.建库2
    mysql> create schema db02;
    Query OK, 1 row affected (0.00 sec)
    
    #3.创建已存在的库不报错
    mysql> create database db01;
    ERROR 1007 (HY000): Can't create database 'db01'; database exists
    
    mysql> create database IF NOT EXISTS db01;
    Query OK, 1 row affected, 1 warning (0.00 sec)
    

    3)查看建库语句

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

    4)创建库指定字符集和校验规则

    #1.指定字符集建库
    mysql> create database db03 character set utf8;
    Query OK, 1 row affected (0.00 sec)
    
    #2.指定字符集和校验规则建库
    mysql> create database db04 character set utf8 collate utf8_general_ci;
    Query OK, 1 row affected (0.00 sec)
    
    mysql> create database db06 charset utf8 collate utf8_general_ci;
    Query OK, 1 row affected (0.00 sec)
    

    5)修改库

    #只需要修改字符集和校验规则
    mysql> alter database db05 character set utf8mb4 collate utf8mb4_general_ci;
    Query OK, 1 row affected (0.00 sec)
    
    mysql> show create database db05;
    +----------+------------------------------------------------------------------+
    | Database | Create Database                                                  |
    +----------+------------------------------------------------------------------+
    | db05     | CREATE DATABASE `db05` /*!40100 DEFAULT CHARACTER SET utf8mb4 */ |
    +----------+------------------------------------------------------------------+
    1 row in set (0.00 sec)
    

    6)删库

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

    2. create 操作表

    1)查看语法

    mysql> help create table;
    Syntax:
    CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name
        (create_definition,...)
        [table_options]
        [partition_options]
    
    CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name
        [(create_definition,...)]
        [table_options]
        [partition_options]
        [IGNORE | REPLACE]
        [AS] query_expression
    
    CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name
        { LIKE old_tbl_name | (LIKE old_tbl_name) }
    

    2)建表

    #1.进入库
    mysql> use test;
    Database changed
    
    #2.查看所在库
    mysql> select database();
    +------------+
    | database() |
    +------------+
    | test      |
    +------------+
    1 row in set (0.00 sec)
    
    #3.建表
    mysql> create table tb1(id int);
    Query OK, 0 rows affected (0.01 sec)
    

    3)数据类型

    int			整数			-2^31 --- 2^31-1   (-2147483648 - 2147483647)
    tinyint		最小整数	    -128 --- 127	  #一般用在定义年龄
    varchar		字符类型(变长)	#身份证或者名字
    char		字符类型(定长)
    enum		枚举类型		  #性别
    datetime	时间类型
    

    4)测试int数据类型

    #1.建表
    mysql> create table tb1(id int);
    Query OK, 0 rows affected (0.01 sec)
    
    #2.指定字符集建表
    mysql> create table tb2(id int) charset utf8;
    Query OK, 0 rows affected (0.01 sec)
    
    #3.查看建表语句
    mysql> show create table tb2;
    +-------+---------------------------------------------------------------------------------------+
    | Table | Create Table                                                                          |
    +-------+---------------------------------------------------------------------------------------+
    | tb2   | CREATE TABLE `tb2` (
      `id` int(11) DEFAULT NULL
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8 |
    +-------+---------------------------------------------------------------------------------------+
    1 row in set (0.01 sec)
    
    #4.查看表结构
    mysql> desc tb1;
    +-------+---------+------+-----+---------+-------+
    | Field | Type    | Null | Key | Default | Extra |
    +-------+---------+------+-----+---------+-------+
    | id    | int(11) | YES  |     | NULL    |       |
    +-------+---------+------+-----+---------+-------+
    1 row in set (0.00 sec)
    
    #5.插入数据
    mysql> insert tb1 values('11111111111');
    ERROR 1264 (22003): Out of range value for column 'id' at row 1
    
    mysql> insert tb1 values('-2147483648');
    Query OK, 1 row affected (0.00 sec)
    
    mysql> insert tb1 values('2147483648');
    ERROR 1264 (22003): Out of range value for column 'id' at row 1
    
    mysql> insert tb1 values('-2147483649');
    ERROR 1264 (22003): Out of range value for column 'id' at row 1
    
    mysql> insert tb1 values('2147483647');
    Query OK, 1 row affected (0.00 sec)
    #原因:插入的数据超过数据类型的长度
    

    5)测试char和varchar类型

    #1.建表
    mysql> create table tb1(id int,name varchar(12));
    Query OK, 0 rows affected (0.06 sec)
    
    #2.插入数据
    mysql> insert into tb1 values('1','邱导');
    Query OK, 1 row affected (0.00 sec)
    
    mysql> insert into tb1 values('1','zengzhigaoxiang');
    ERROR 1136 (21S01): Column count doesn't match value count at row 1
    #字符超过数据类型的限制值
    

    6)测试enum类型

    #1.建表
    mysql> create table tb4(id int,name varchar(10),sex enum('man','woman'));
    Query OK, 0 rows affected (0.03 sec)
    
    #2.插入数据
    mysql> insert into tb4 values('1','邱导','man');
    Query OK, 1 row affected (0.00 sec)
    
    mysql> insert into tb4 values('2','刘大维','nan');
    ERROR 1265 (01000): Data truncated for column 'sex' at row 1
    #如果是枚举类型,必须插入类型指定的值,不能插入额外的值
    

    7)建表测试

    #建学生表
    id
    name
    sex
    age
    cometime
    
    #1.建表
    mysql> create table student(id int,name varchar(10),sex enum('男','nv'),age tinyint,cometime datetime);
    Query OK, 0 rows affected (0.03 sec)
    
    #2.插入数据
    mysql> insert into student values('-12573','邱导','男','-18',now());
    Query OK, 1 row affected (0.00 sec)
    
    #3.查看数据
    mysql> select * from student;
    +--------+--------+------+------+---------------------+
    | id     | name   | sex  | age  | cometime            |
    +--------+--------+------+------+---------------------+
    | -12573 | 邱导   | 男   |  -18 | 2020-10-23 18:40:15 |
    +--------+--------+------+------+---------------------+
    1 row in set (0.00 sec)
    

    8)建表的数据属性

    not null: 			非空
    primary key: 		主键(唯一且非空的)
    auto_increment: 	自增(此列必须是:primary key或者unique key)
    unique key: 		唯一键(单独的唯一的)
    default: 			默认值
    unsigned: 			非负数
    comment:			注释
    

    9)加上数据属性建表

    #1.建表
    mysql> create table student(
        -> id int unsigned primary key auto_increment comment '学生id',
        -> name varchar(10) not null comment '学生姓名',
        -> sex enum('男','女') default '男' comment '学生性别',
        -> age tinyint unsigned comment '学生年龄',
        -> cometime datetime default now() comment '入学时间',
        -> class varchar(12) not null comment '学生班级',
        -> status enum('0','1') default 1 comment '学生状态');
    Query OK, 0 rows affected (0.01 sec)
    
    #2.查看建表语句
    mysql> show create table student;
                                                                             
    | student | CREATE TABLE `student` (
      `id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '学生id',
      `name` varchar(10) NOT NULL COMMENT '学生姓名',
      `sex` enum('男','女') DEFAULT '男' COMMENT '学生性别',
      `age` tinyint(3) unsigned DEFAULT NULL COMMENT '学生年龄',
      `cometime` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '入学时间',
      `class` varchar(12) NOT NULL COMMENT '学生班级',
      `status` enum('0','1') DEFAULT '0' COMMENT '学生状态',
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8                              |
    
    1 row in set (0.00 sec)
    
    #3.插入数据
    mysql> insert into student(name,class) values('邱导','Linux10期');
    Query OK, 1 row affected (0.00 sec)
    mysql> insert into student(name,class) values('刘大维','Linux10期');
    Query OK, 1 row affected (0.00 sec)
    mysql> insert into student(name,class) values('虞陈宇','Linux10期');
    Query OK, 1 row affected (0.00 sec)
    mysql> insert into student(name,age,class) values('周昊','18','Linux10期');
    Query OK, 1 row affected (0.00 sec)
    
    #4.查看数据
    mysql> select * from student;
    +----+-----------+------+------+---------------------+------------+--------+
    | id | name      | sex  | age  | cometime            | class      | status |
    +----+-----------+------+------+---------------------+------------+--------+
    |  1 | 邱导      | 男   | NULL | 2020-10-23 19:06:25 | Linux10期  | 0      |
    |  2 | 邱导      | 男   | NULL | 2020-10-23 19:07:31 | Linux10期  | 0      |
    |  3 | 刘大维    | 男   | NULL | 2020-10-23 19:07:57 | Linux10期  | 0      |
    |  4 | 虞陈宇    | 男   | NULL | 2020-10-23 19:08:17 | Linux10期  | 0      |
    |  5 | 周昊      | 男   |   18 | 2020-10-23 19:09:44 | Linux10期  | 0      |
    +----+-----------+------+------+---------------------+------------+--------+
    5 rows in set (0.00 sec)
    

    10)删除表

    mysql> drop table student;
    Query OK, 0 rows affected (0.00 sec)
    

    11)修改表

    #1.修改表字符集
    mysql> alter table play charset utf8mb4;
    Query OK, 0 rows affected (0.03 sec)
    Records: 0  Duplicates: 0  Warnings: 0
    
    #2.修改表名
    mysql> alter table play rename student;
    Query OK, 0 rows affected (0.01 sec)
    
    #3.给表插入字段
    mysql> alter table student add name varchar(10);
    
    #4.给表插入多个字段
    mysql> alter table student add sex enum('男','女'),add age tinyint;
    
    #5.插入字段到第一列
    mysql> alter table student add id int first;
    
    #6.插入字段到指定字段后面
    mysql> alter table student add class varchar(12) after id;
    
    #7.删除字段
    mysql> alter table student drop qiudao;
    
    #8.修改列属性
    mysql> alter table student modify name varchar(20);
    
    #9.修改列的名字和属性
    mysql> alter table student change sex xingbie enum('男','女');
    

    三、DCL--数据控制语言

    1.授权命令 grant

    #1.授权
    grant all on *.* to root@'172.16.1.%' identified by '123';
    #应该授权低一点的权限
    grant select,update,insert on database.* to dev@'172.16.1.%' identified by 'Lhd@123456'
    
    #2.查看用户权限
    mysql> show grants for root@'localhost';
    
    #3.特殊权限授权
    max_queries_per_hour:一个用户每小时可发出的查询数量
    max_updates_per_hour:一个用户每小时可发出的更新数量
    
    max_connections_per_hour:一个用户每小时可连接到服务器的次数
    mysql> grant all on *.* to lhd@'localhost' identified by '123' with max_connections_per_hour 1;
    
    max_user_connections:允许同时连接数量
    mysql> grant all on *.* to test@'localhost' identified by '123' with max_user_connections 2;
    

    2.回收权限 revoke

    #1.回收权限
    mysql> revoke drop on *.* from test@'localhost';
    
    #2.查看权限
    mysql> show grants for test@'localhost';
    
    #3.所有权限
    SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, GRANT, 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 TABLESPACE
    

    3.授权一个超级管理员

    mysql> grant all on *.* to superuser@'localhost' identified by 'Lhd@123456' with grant option;
    

    四、DML--数据操作语言

    1.insert命令

    #1.插入数据之前先看表结构
    mysql> desc student;
    +----------+---------------------+------+-----+-------------------+----------------+
    | Field    | Type                | Null | Key | Default           | Extra          |
    +----------+---------------------+------+-----+-------------------+----------------+
    | id       | int(10) unsigned    | NO   | PRI | NULL              | auto_increment |
    | name     | varchar(10)         | NO   |     | NULL              |                |
    | sex      | enum('男','女')     | YES  |     | 男                |                |
    | age      | tinyint(3) unsigned | YES  |     | NULL              |                |
    | cometime | datetime            | YES  |     | CURRENT_TIMESTAMP |                |
    | class    | varchar(12)         | NO   |     | NULL              |                |
    | status   | enum('0','1')       | YES  |     | 0                 |                |
    +----------+---------------------+------+-----+-------------------+----------------+
    7 rows in set (0.00 sec)
    
    #2.insert不规范写法
    mysql> insert student values('4','周昊','男','20','2020-10-23','Linux10','0');
    #一个字段都不能少
    
    #3.规范的写法(只插入需要的值)
    mysql> insert student(name,class) values('邱导','linux10');
    mysql> insert student(name,class,age) values('邱导','linux10',20);
    
    #4.规范写法插入多条数据
    mysql> insert student(name,class,age) values('增加','linux10',20),('减少','linux10',30);
    

    2.update语句

    #1.修改数据之前一定要确认数据
    mysql> select * from student;
    
    #2.修改数据,错误写法
    mysql> update student set age='16';
    
    #3.修改数据,正确写法
    mysql> update student set age='18' where id=1;
    
    #4.如果说就是修改表中所有数据
    mysql> update student set age='18' where 1=1;
    

    3.delete语句

    #1.错误语法
    mysql> delete from student;
    
    #2.正确写法
    mysql> delete from student where id=1;
    
    #3.删除
    mysql> delete from student where name='增加' and cometime='2020-10-23 20:16:57';
    
    #4.使用状态列表示已删除
    mysql> update student set status='1' where id=9;
    mysql> select * from student where status='0';
    

    4.注意

    1.操作数据时一定要查看数据
    2.修改和删除数据时一定要加条件
    3.使用条件时尽量使用主键字段
    4.如果没有主键字段,使用多条件的方式
    5.如果有状态列,使用状态列表示数据已删除
    

    一、DQL 数据查询语言

    1.select 简单查询命令

    #1.查询表中所有的数据
    mysql> select * from test.student;
    
    #2.查看所有数据之前,先查看数据量
    mysql> select count(*) from test.student;
    
    #3.查询指定列
    mysql> select user,host from mysql.user;
    
    #4.按条件查询
    mysql> select * from test.student where id='8';
    mysql> select id,name from test.student where id='8';
    

    2.查询数据测试

    1)将sql导入数据库

    #上传sql文件到服务器
    [root@db01 ~]# rz world.sql
    
    #导入sql到数据库
    mysql> source /root/world.sql;
    mysql> . /root/world.sql
    

    2)查询的操作

    #1.查看库下面的表
    mysql> show tables from world;
    
    mysql> use world
    mysql> show tables;
    +-----------------+
    | Tables_in_world |
    +-----------------+
    | city            |
    | country         |
    | countrylanguage |
    +-----------------+
    3 rows in set (0.00 sec)
    
    #2.查看表结构
    mysql> desc city;
    
    #3.查询所有数据
    mysql> select count (*) from city;
    mysql> select * from city;
    
    #4.查询指定列数据
    mysql> select name,population from city;
    
    #5.按照人口数量排序
    #升序
    mysql> select name,population from city order by population;
    #降序
    mysql> select name,population from city order by population desc;
    
    #6.查看人口数量最多排名前十的城市
    mysql> select name,population from city order by population desc limit 10;
    
    #7.按照步长查询数据
    #查询数据从10后面开始计算,展示20条数据,20就是步长
    mysql> select id,name,population from city limit 10,20;
    
    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的连接符:and or like in
    
    #2.查看中国城市的人口数量
    mysql> select CountryCode,name,population from city where CountryCode='CHN';
    
    #3.查看黑龙江省城市的人口数量
    mysql> select CountryCode,District,name,population from city where CountryCode='CHN' and District='heilongjiang';
    
    #4.查询中国人口数量小于10万的城市
    mysql> select CountryCode,population,name from city where CountryCode='CHN' and population<'100000';
    
    #5.查看国家代码以H开头的
    mysql> select * from city where CountryCode like 'H%';
    
    #6.查看国家代码以H结尾的
    mysql> select * from city where CountryCode like '%H';
    
    #7.查看国家代码包含H的
    mysql> select * from city where CountryCode like '%H%';
    
    #8.查询中国城市和美国城市的人口数量
    mysql> select CountryCode,name,population from city where CountryCode='CHN' or CountryCode='USA';
    mysql> select CountryCode,name,population from city where CountryCode in ('CHN','USA');
    
    #9.联合查询
    mysql> select CountryCode,name,population from city where CountryCode='CHN' union all select CountryCode,name,population from city where CountryCode='USA';
    

    二、select 高级用法(多表联查,连表查询)

    1.传统连接

    1)数据

    [qiudao,zengdao,qiandao]
    [80,90,100]
    
    #建表
    id:[1,2,3]
    name:[qiudao,zengdao,qiandao]
    
    #建表
    id:[1,2,3]
    mark:[80,90,100]
    

    2)建表

    #建立学生表
    mysql> create table student1(id int,name varchar(20));
    
    #建立成绩表
    mysql> create table score(id int,mark int);
    

    3)插入数据

    #插入学生表数据
    mysql> insert student1 values('1','qiudao'),('2','zengdao'),('3','qiandao');
    
    #插入成绩表数据
    mysql> insert score values('1','80'),('2','90'),('3','100');
    

    4)查看数据

    #查看学生表
    mysql> select * from student1;
    +------+---------+
    | id   | name    |
    +------+---------+
    |    1 | qiudao  |
    |    2 | zengdao |
    |    3 | qiandao |
    +------+---------+
    3 rows in set (0.00 sec)
    
    #查看成绩表
    mysql> select * from score;
    +------+------+
    | id   | mark |
    +------+------+
    |    1 |   80 |
    |    2 |   90 |
    |    3 |  100 |
    +------+------+
    3 rows in set (0.00 sec)
    

    5)数据查询

    #查看qiudao的成绩
    
    1.方式一:
    mysql> select student1.name,score.mark from student1,score where student1.id='1' and score.id='1';
    
    2.方式二:
    mysql> select student1.name,score.mark from student1,score where student1.id=score.id and name='qiudao';
    

    6)查询题1:

    #查询世界上小于100人的城市是哪个国家的?
    
    #1.审题:查看需要查询哪些数据
    城市名字   城市人口数量   国家名字
    
    #2.找到查询内容的字段在哪个表
    城市名字        城市人口数量          国家名字
    city.name      city.population		country.name
    
    #3.找出两个表中关联的列
    city.countrycode
    country.code
    
    #4.编写语句
    select city.name,city.population,country.name from city,country where city.countrycode=country.code  and city.population < '100';
    
    select city.name,city.population,country.name from city natural join country where city.population < '100';
    

    7)多表联查练习题2:

    #查询世界上小于100人的城市是哪个国家的,使用什么语言?
    
    #1.审题:查看需要查询哪些数据
    城市名字   城市人口数量   国家名字   国家的语言
    
    #2.找到查询内容的字段在哪个表
    城市名字        城市人口数量          国家名字		国家的语言
    city.name      city.population		country.name    countrylanguage.language
    
    #3.找出三个表相关联的列
    city.countrycode
    country.code
    countrylanguage.CountryCode
    
    #4.编写语句
    select city.name,city.population,country.name,countrylanguage.language from city,country,countrylanguage where city.countrycode=country.code and country.code=countrylanguage.CountryCode and city.population < '100';
    

    2.自连接

    #自连接会自动关联两个表中数据相同的字段,自连接的两个表必须有相同的字段和数据
    

    1)自连接查询

    #查询人口数量大于100万的城市,列出他们的国家代码和国家语言
    
    1.传统连接:
    select city.name,city.population,countrylanguage.CountryCode,countrylanguage.language from city,countrylanguage where countrylanguage.CountryCode=city.CountryCode and city.population > '1000000';
    
    2.自连接:
    select city.name,city.population,countrylanguage.CountryCode,countrylanguage.language from city natural join countrylanguage where city.population > '1000000';
    
    #注意:
    	1.自连接会自动去获取两个表之间的关联列和数据,所以自连接的两个表必须有相同的字段和数据
    

    3.内连接

    1)语法

    select * from 表1 join 表2 on 关联条件 where 条件
    
    #注意:
    	表 1 是小表
    	表 2 是大表
    

    2)例子:

    #查询世界上小于100人的城市是哪个国家的,国家代码是什么
    
    1.传统链接:
    select city.population,city.name,country.name,country.code from city,country where country.code=city.countrycode and city.population < '100';
    
    2.内连接:
    select city.population,city.name,country.name,country.code from country join city on country.code=city.countrycode where city.population < '100';
    

    3)内连接三表联查

    #查询世界上小于100人的城市是哪个国家的,用什么语言?
    select city.population,city.name,country.name,countrylanguage.language from country join city on city.countrycode=country.code join countrylanguage on country.code=countrylanguage.countrycode where city.population < '100';
    

    4.外连接

    1)左外连接

    select city.name,city.countrycode,country.name 
    from city left join country 
    on city.countrycode=country.code 
    and city.population<100;
    

    2)右外连接

    select city.name,city.countrycode,country.name 
    from city right join country 
    on city.countrycode=country.code 
    and city.population<100;
    

    5.UNION(合并查询)

    #范围查询OR语句
    mysql> select * from city where countrycode='CHN' or countrycode='USA';
    
    #范围查询IN语句
    mysql> select * from city where countrycode in ('CHN','USA');
    
    #替换为:
    mysql> select * from city where countrycode='CHN' 
    union all
    select * from city where countrycode='USA' limit 10;
    
  • 相关阅读:
    Anaconda+Vscode+opencv3环境打造
    关于AXI4-Stream Infrastucture IP的学习
    Xilinx的License问题
    IOBUF的使用
    Vscode的学习
    关于ZYNQ 7 processing system IP的设置导出与导入
    使用zynq verification IP进行系统验证
    使用AXI Verifcation IP进行系统验证
    MIG IP学习笔记
    Git的GUI工具sourcetree的使用
  • 原文地址:https://www.cnblogs.com/xiaolang666/p/13864028.html
Copyright © 2011-2022 走看看