[Database] MySQL basic syntax

Mysql basics


Insert picture description here

Database and table creation

  • Show database

     SHOW DATABASES;
    
  • Create database

    # utf-8
      CREATE DATABASE 数据库名称 DEFAULT CHARSET utf8 COLLATE utf8_general_ci;
     
      # gbk
      CREATE DATABASE 数据库名称 DEFAULT CHARACTER SET gbk COLLATE gbk_chinese_ci;
    
  • Open the database

    USE db_name;
      注:每次使用数据库必须打开相应数据库
    
  • User Management

    创建用户
        create user '用户名'@'IP地址' identified by '密码';
    删除用户
        drop user '用户名'@'IP地址';
    修改用户
        rename user '用户名'@'IP地址'; to '新用户名'@'IP地址';;
    修改密码
        set password for '用户名'@'IP地址' = Password('新密码')
      
    PS:用户权限相关数据保存在mysql数据库的user表中,所以也可以直接对其进行操作(不建议)
    
    
    show grants for '用户'@'IP地址'                  -- 查看权限
    grant  权限 on 数据库.表 to   '用户'@'IP地址'      -- 授权
    revoke 权限 on 数据库.表 from '用户'@'IP地址'      -- 取消权限
    
    
  • Backup library and restore library

    1. MySQL backup and restore under Windows

    备份 
    1、开始菜单 | 运行 | cmd |利用“cd /Program Files/MySQL/MySQL Server 5.0/bin”命令进入bin文件夹 
    2、利用“mysqldump  -u 用户名 -p databasename >exportfilename”导出数据库到文件,如mysqldump -u root -p voice>voice.sql,然后输入密码即可开始导出。 
      
    还原 
    1、进入MySQL Command Line Client,输入密码,进入到“mysql>”。
    2、输入命令"show databases;",回车,看看有些什么数据库;建立你要还原的数据库,输入"create database voice;",回车。
    3、切换到刚建立的数据库,输入"use voice;",回车;导入数据,输入"source voice.sql;",回车,开始导入,再次出现"mysql>"并且没有提示错误即还原成功。 
    

    2. MySQL backup and restore under linux

    2.1 备份(利用命令mysqldump进行备份)
       [root@localhost mysql]# mysqldump -u root -p voice>voice.sql,输入密码即可。
    2.2 还原
    方法一:
       [root@localhost ~]# mysql -u root -p 回车,输入密码,进入MySQL的控制台"mysql>",同1.2还原。
    方法二:
       [root@localhost mysql]# mysql -u root -p voice<voice.sql,输入密码即可。
    

Data table creation

  • Show data table

    show tables;
    
  • Create data table

    create table 表名(
        列名  类型  是否可以为空,
        列名  类型  是否可以为空
    )ENGINE=InnoDB DEFAULT CHARSET=utf8
    
    • Whether the setting can be empty

      是否可空,null表示空,非字符串
                  not null    - 不可空
                  null        - 可空
      
    • Set default

       默认值,创建列时可以指定默认值,当插入数据时如果未主动设置,则自动添加默认值
                  create table tb1(
                      nid int not null defalut 2,
                      num int not null
                  )
      
    • Set up

             自增,如果为某列设置自增列,插入数据时无需设置此列,默认将自增(表中只能有一个自增列)
                  create table tb1(
                      nid int not null auto_increment primary key,
                      num int null
                  )
                  create table tb1(
                      nid int not null auto_increment,
                      num int null,
                      index(nid)
                  )
                  注意:1、对于自增列,必须是索引(含主键)。
                       2、对于自增可以设置步长和起始值
                           show session variables like 'auto_inc%';
                           set session auto_increment_increment=2;
                           set session auto_increment_offset=10;
      
                           shwo global  variables like 'auto_inc%';
                           set global auto_increment_increment=2;
                           set global auto_increment_offset=10;
      
    • Set primary key

       主键,一种特殊的唯一索引,不允许有空值,如果主键使用单个列,则它的值必须唯一,如果是多列,则其组合必须唯一。
                  create table tb1(
                      nid int not null auto_increment primary key,
                      num int null
                  )
                  create table tb1(
                      nid int not null,
                      num int not null,
                      primary key(nid,num)
                  )
      
    • Set foreign key

      外键,一个特殊的索引,只能是指定内容
                  create table color(
                      nid int not null primary key,
                      name char(16) not null
                  )
      
                  create table fruit(
                      nid int not null primary key,
                      smt char(32) null ,
                      color_id int not null,
                      constraint fk_cc foreign key (color_id) references color(nid)
                  )
      
      设置外键
      
  • Delete table

    drop table 表名
    
  • Empty table

    delete from 表名
    truncate table 表名
    
  • Basic data type

    Basic data types in MySQL
    bit[(M)]
    binary bit (101001), m represents the length of the binary bit (1-64), default m=1

    tinyint[(m)] [unsigned] [zerofill]

    small integer, the data type is used to save some ranges The integer value range of:
    signed:
    -128 ~ 127.
    Unsigned:
    ~ 255

    Special: There is no Boolean value in MySQL, use tinyint(1) structure.

    int[(m)][unsigned] [zerofill]

    integer, the data type is used to save some range of integer value range:
    signed:
    -2147483648 to 2147483647
    unsigned:
    to 4294967295

    special: m in integer type is only used for display , There is no limit to the storage range. For example: int(5), when inserting data 2, the data displayed when selecting is: 00002

    bigint[(m)][unsigned] [zerofill]
    big integer, the data type is used to save some range of integer value range:
    signed:
    -9223372036854775808 ~ 9223372036854775807
    Unsigned:
    ~ 18446744073709551615

    decimal[(m[,d]) ] [unsigned] [zerofill]
    The exact decimal value, m is the total number of digits (negative sign is not counted), d is the number after the decimal point. The maximum value of m is 65 and the maximum value of d is 30.

    Special: For accurate numerical calculations, this type of
    decaimal is needed to store accurate values ​​because of its internal storage as a string.

    FLOAT[(M,D)] [UNSIGNED] [ZEROFILL]
    Single-precision floating-point number (non-exact decimal value), m is the total number of digits, and d is the number after the decimal point.
    Unsigned:
    -3.402823466E+38 to -1.175494351E-38,
    1.175494351E-38 to 3.402823466E+38
    Signed:
    1.175494351E-38 to 3.402823466E+38

    **** The larger the value, the less accurate*** *

    DOUBLE[(M,D)] [UNSIGNED] [ZEROFILL]
    Double-precision floating-point number (non-exact decimal value), m is the total number of digits, and d is the number after the decimal point.

    Unsigned:
    -1.7976931348623157E+308 to -2.2250738585072014E-308
    2.2250738585072014E-308 to 1.7976931348623157E+308
    Signed:
    2.2250738585072014E-308 to 1.7976931348623157E+308
    **** The larger the value, the less accurate ****


    char (m)
    The char data type is used to represent a fixed-length character string, which can contain up to 255 characters. Where m represents the length of the string.
    PS: Even if the data is less than m length, it will occupy m length.
    varchar(m)
    varchars data type is used for variable-length strings, which can contain up to 255 characters. Where m represents the maximum length of the string allowed to be saved in the data type, as long as the string length is less than the maximum value, it can be saved in the data type.

    Note: Although varchar is more flexible to use, from the perspective of the performance of the entire system, the processing speed of the char data type is faster, and sometimes it can even exceed 50% of the processing speed of varchar. Therefore, users should comprehensively consider various factors when designing a database to achieve the best balance. The

    text
    text data type is used to store large strings of variable length, which can group up to 65535 (2 16 − 1) characters.

    mediumtext
    A TEXT column with a maximum length of 16,777,215 (2
    24 − 1) characters.

    longtext
    A TEXT column with a maximum length of 4,294,967,295 or 4GB (2**32 − 1) characters.


    enum
    enumeration type,
    An ENUM column can have a maximum of 65,535 distinct elements. (The practical limit is less than 3000.)
    Example:
    CREATE TABLE shirts (
    name VARCHAR(40),
    size ENUM(‘x-small’, ‘small’, ‘medium’, ‘large’, ‘x-large’)
    );
    INSERT INTO shirts (name, size) VALUES (‘dress shirt’,‘large’), (‘t-shirt’,‘medium’),(‘polo shirt’,‘small’);

    set
    集合类型
    A SET column can have a maximum of 64 distinct members.
    示例:
    CREATE TABLE myset (col SET(‘a’, ‘b’, ‘c’, ‘d’));
    INSERT INTO myset (col) VALUES (‘a,d’), (‘d,a’), (‘a,d,a’), (‘a,d,d’), (‘d,a,d’);

    DATE
    YYYY-MM-DD(1000-01-01/9999-12-31)

    TIME
    HH:MM:SS(’-838:59:59’/‘838:59:59’)

    YEAR
    YYYY(1901/2155)

    DATETIME

    YYYY-MM-DD HH:MM:SS(1000-01-01 00:00:00/9999-12-31 23:59:59 Y)

    TIMESTAMP

    YYYYMMDD HHMMSS (1970-01-01 00:00:00/2037 at some time)

Modify table

添加列:alter table 表名 add 列名 类型
删除列:alter table 表名 drop column 列名
修改列:
        alter table 表名 modify column 列名 类型;  -- 类型
        alter table 表名 change 原列名 新列名 类型; -- 列名,类型
  
添加主键:
        alter table 表名 add primary key(列名);
删除主键:
        alter table 表名 drop primary key;
        alter table 表名  modify  列名 int, drop primary key;
  
添加外键:alter table 从表 add constraint 外键名称(形如:FK_从表_主表) foreign key 从表(外键字段) references 主表(主键字段);
删除外键:alter table 表名 drop foreign key 外键名称
  
修改默认值:ALTER TABLE testalter_tbl ALTER i SET DEFAULT 1000;
删除默认值:ALTER TABLE testalter_tbl ALTER i DROP DEFAULT;

修改表

Table relationship

  • Association mapping

    • One-to-many / many-to-one

      One-to-many : From the perspective of the team, a team with multiple players is one-to-many

      Many-to-one : From the perspective of players, multiple players belong to the same team as many-to-one

      The one-to-many relationship between data tables is as follows:

      img

    • One to one

      There are two manifestations of one-to-one relationships between data tables, one is foreign key association and the other is primary key association. The icons are as follows:

      One-to-one foreign key association:

      img

      One-to-one primary key association: the primary keys of the two tables must be exactly the same, and the relationship is established through the primary keys of the two tables

      img

    • Many to many

      The many-to-many relationship in the database generally needs to be processed in the way of an intermediate table, which converts the many-to-many into two-to-many

      img

Constraints between data tables

In MYSQL, several commonly used constraints:

img


Operation of database and table content (add, delete, modify, check)

  • increase
insert into 表 (列名,列名...) values (值,值,值...)
insert into 表 (列名,列名...) values (值,值,值...),(值,值,值...)
insert into 表 (列名,列名...) select (列名,列名...) from 表
  • delete
delete from 表
delete from 表 where id=1 and name='alex'
  • change
update 表 set name = 'alex' where id>1
  • check

4.1, general query

select * from 表
select * from 表 where id > 1
select nid,name,gender as gg from 表 where id > 1

More options query

  • Data sorting (query)
排序
    select * from 表 order by 列 asc              - 根据 “列” 从小到大排列
    select * from 表 order by 列 desc             - 根据 “列” 从大到小排列
    select * from 表 order by 列1 desc,列2 asc    - 根据 “列1” 从大到小排列,如果相同则按列2从小到大排序
  • Fuzzy query
通配符(模糊查询)
    select * from 表 where name like 'ale%'  - ale开头的所有(多个字符串)
    select * from 表 where name like 'ale_'  - ale开头的所有(一个字符)
  • Aggregate function query
1)COUNT
        语法:COUNT(e1)
        参数:e1为一个表达式,可以是任意的数据类型
        返回:返回数值型数据
        作用:返回e1指定列不为空的记录总数

2)SUM,
        语法:SUM(e1)
        参数:e1为类型为数值型的表达式
        返回:返回数值型数据
        作用:对e1指定的列进行求和计算

3)MIN, MAX
        语法:MIN(e1)、MAX(e1)
        参数:e1为一个字符型、日期型或数值类型的表达式。
            若e1为字符型,则根据ASCII码来判断最大值与最小值。
        返回:根据e1参数的类型,返回对应类型的数据。
        作用:MIN(e1)返回e1表达式指定的列中最小值;
              MAX(e1)返回e1表达式指定的列中最大值;

4)AVG
        语法:AVG(e1)
        参数:e1为一个数值类型的表达式
        返回:返回一个数值类型数据
        作用:对e1表达式指定的列,求平均值。

5)MEDIAN
        语法:MEDIAN(e1)
        参数:e1为一个数值或日期类型的表达式
        返回:返回一个数值或日期类型的数据
        作用:首先,根据e1表达式指定的列,对值进行排序;
            若排序后,总记录为奇数,则返回排序队列中,位于中间的值;
            若排序后,总记录为偶数,则对位于排序队列中,中间两个值进行求平均,返回这个平均值;
6)RANK
        1)用法1:RANK OVER
               语法:    RANK( )  OVER ([ PARTITION BY column1 ] ORDER BY column2 [ASC|DESC])
                为分析函数,为每条记录产生一个序列号,并返回。
               参数:    column1为列名,指定按照哪一列进行分类(分组)
                  column2为列名,指定根据哪列排序,默认为升序;
                  若指定了分类子句(PARTITION BY),则对每类进行排序(每个分类单独排序)
               返回:返回一个数值类型数据,作为该记录的序号!
               作用:为分析函数,对记录先按column1分类,再对每个分类进行排序,并为每条记录分配一个序号(每个分类单独排序)
               注意:排序字段值相同的记录,分配相同的序号。存在序号不连续的情况    
               实例:student表记录了学生每科的成绩,要求按学科排序,并获取每科分数前两名的记录
                student表如下:        
                SQL> select * from student order by kemu;
                 NAME       ID                KEMU      FENSHU
                ---------- -------------- -------------- ----------------
                Li            0113101     物理               80
                Luo         0113011     物理               80
                Wang     0113077     物理               70
                Zhang     0113098    物理               90
                Luo         0113011     高数               80
                Wang      0113077    高数               70
                Zhang     0113098    高数               80
                Li             0113101    高数               90
rows selected
                按学科分类,按成绩排序(降序)
                SQL> select rank() over(partition by KEMU order by FENSHU desc) as sort,student.* from student;
                       SORT    NAME        ID              KEMU      FENSHU
                ---------- ---------- ---------------- ------------ ----------
           Zhang      0113098    物理               90
           Li              0113101    物理               80
           Luo           0113011    物理               80
           Wang       0113077    物理               70
           Li              0113101    高数               90
           Luo           0113011    高数               80
           Zhang      0113098    高数               80
           Wang       0113077    高数               70
                由返回记录可了解,对排序列的值相同的记录,rank为其分配了相同的序号(SORT NAME列)。
                并且之后的记录的序号是不连续的。
                若获取每科前两名,只需对排序后的结果增加二次查询即可
                 select * from 
                    (select rank() over(partition by KEMU order by FENSHU desc) as sort_id,student.* from student) st 
                 where st.sort_id<=2;
    
        2)用法2:RANK WITHIN GROUP
            语法: RANK( expr1 ) WITHIN GROUP ( ORDER BY expr2 )
                为聚合函数,返回一个值。
            参数:expr1为1个或多个常量表达式;
                         expr2为如下格式的表达式:    
                          expr2的格式为'expr3 [ DESC | ASC ] [ NULLS { FIRST | LAST } ]'
                其中,expr1需要与expr2相匹配,
                    即:expr1的常量表达式的类型、数量必须与ORDER BY子句后的expr2表达式的类型、数量相同
                    实际是expr1需要与expr3相匹配
                    如:RANK(a) WITHIN GROUP (ORDER BY b ASC NULLS FIRST);
                        其中,a为常量,b需要是与相同类型的表达式
                        RANK(a,b) WITHIN GROUP (ORDER BY c DESC NULLS LAST, d DESC NULLS LAST);
                        其中,a与b都为常量;c是与a类型相同的表达式、d是与b类型相同的表达式;
                
            返回:返回数值型数据,该值为假定记录在表中的序号。
            作用:确定一条假定的记录,在表中排序后的序号。
               如:假定一条记录(假设为r1)的expr2指定字段值为常量expr1,则将r1插入表中后,
                与原表中的记录,按照ORDER BY expr2排序后,该记录r1在表中的序号为多少,返回该序号。
            注释: NULLS FIRST指定,将ORDER BY指定的排序字段为空值的记录放在前边;
                NULLS LAST指定,将ORDER BY指定的排序字段为空值的记录放在后边;
            实例:假设一个员工的薪水为1500,求该员工的薪水在员工表中的排名为多少?
                已知员工表如下:
                SQL> select * from employees;
                EMP_ID     EMP_NAME     SALARY
                ---------- -------------------- ---------------
     ZhangSan             500
     LiSi                         1000
     WangWu               1500
     MaLiu                     2000
     NiuQi                      2500

                SQL> select rank(1500) within group (order by salary) as "rank number" from employees;
                rank number
                -----------
                由结果可知,薪水为1500的员工,在表中按升序排序,序号为3
                
7)FIRST、LAST
        语法:    agg_function(e1) KEEP (DENSE_RANK FIRST ORDER BY e2 [NULLS {FIRST|LAST}]) [OVER PARTITION BY e3 ]
            agg_function(e1) KEEP (DENSE_RANK LAST  ORDER BY e2 [NULLS {FIRST|LAST}]) [OVER PARTITION BY e3 ]                  
        参数:    agg_function为一个聚合函数,可以为 MIN、MAX、SUM、AVG、COUNT、VARIANCE或STDDEV
            e2指定以哪个字段为依据,进行排序;
            e3指定以哪个字段为依据,进行分类(分组);
            当指定OVER PARTITION BY子句后,针对分类后的每个类单独排序;
            DENSE_RANK为排序后的记录分配序号,并且序号为连续的。
            NULLS {FIRST|LAST}指定排序字段e1的值若为空,则拍在序列前边(NULLS FIRST)或者后边(NULLS LAST)
            DENSE_RANK后的FIRST/LAST确定选取通过DENSE_RANK排好序后的序列中,序号最小/最大的记录。序号相同时,返回多条记录
            当序号相同,返回多条记录时,agg_function(e1)聚合函数继续对这多条记录的e1字段做聚合操作。
        作用:    如果agg_function为min(e1),获取排序后的FIRST或LAST的多条记录中,某字段e1的最小值
            该字段不是排序关键字段e2
        实例:
        已知员工表有薪水字段,奖金字段。要求获取薪水最低的员工中,奖金最高的员工的记录。
        已知表内容如下:
        SQL> select * from employees order by salary;
         EMP_ID     EMP_NAME           SALARY  COMMISSION
        ---------- ---------------------------- ------------  ------------
     ZhangSan                    500        200
     LiSi                                500        300
     WangWu                      500        100
     MaLiu                           2000       500
     NiuQi                            2500       200
     ShangDuo                   2500       300
     BaiQi                             2500       400
        
        SQL> select max(commission) keep(dense_rank first order by salary asc) as commission from employees;
        COMMISSION
        ----------
        首先,按salary排序后,获取薪水最低的记录,分别为员工10001、10002、10003三条记录。
        聚合函数max(commission)对3条记录获取奖金最高的为员工10002,奖金为300。

聚集函数
  • Group query
分组
    select num from 表 group by num
    select num,nid from 表 group by num,nid
    select num,nid from 表  where nid > 10 group by num,nid order by nid desc
    select num,nid,count(*),sum(score),max(score),min(score) from 表 group by num,nid
 
    select num from 表 group by num having max(id) > 10
 
    特别的:group by 必须在where之后,order by之前
  • Multi-table query
a、连表
    无对应关系则不显示
    select A.num, A.name, B.name
    from A,B
    Where A.nid = B.nid
 
    无对应关系则不显示
    select A.num, A.name, B.name
    from A inner join B
    on A.nid = B.nid
 
    A表所有显示,如果B中无对应关系,则值为null
    select A.num, A.name, B.name
    from A left join B
    on A.nid = B.nid
 
    B表所有显示,如果B中无对应关系,则值为null
    select A.num, A.name, B.name
    from A right join B
    on A.nid = B.nid
b、组合
    组合,自动处理重合
    select nickname
    from A
    union
    select name
    from B
 
    组合,不处理重合
    select nickname
    from A
    union all
    select name
    from B



Disclaimer: This blog post is a study note and refers to network resources. If there is any infringement, please inform us by private message!

Guess you like

Origin blog.csdn.net/qq_42380734/article/details/105487304