Linux学习-MySQL之SQL语句

Posted 丢爸

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Linux学习-MySQL之SQL语句相关的知识,希望对你有一定的参考价值。

MySQL数据类型

  1. 数值型
    - 精确数值
    int
    decimal
    - 近似数值
    float
    double
    real
  2. 字符型
    定长:char、binary
    变长:varchar、varbinary
    text
    blob
    ENUM,SET
  3. 日期时间型
    date,time,datetime,timestamp
    数据类型定义
    1.值类型
    2.占据存储空间
    3.定长还是变长
    4.如何比较和排序
    5.能否索引
#查看数据库服务器的字符集
mysql> show character set;
+----------+-----------------------------+---------------------+--------+
| Charset  | Description                 | Default collation   | Maxlen |
+----------+-----------------------------+---------------------+--------+
| big5     | Big5 Traditional Chinese    | big5_chinese_ci     |      2 |
| dec8     | DEC West European           | dec8_swedish_ci     |      1 |
| cp850    | DOS West European           | cp850_general_ci    |      1 |
| hp8      | HP West European            | hp8_english_ci      |      1 |
| koi8r    | KOI8-R Relcom Russian       | koi8r_general_ci    |      1 |
| latin1   | cp1252 West European        | latin1_swedish_ci   |      1 |
| latin2   | ISO 8859-2 Central European | latin2_general_ci   |      1 |
| swe7     | 7bit Swedish                | swe7_swedish_ci     |      1 |
| ascii    | US ASCII                    | ascii_general_ci    |      1 |
| ujis     | EUC-JP Japanese             | ujis_japanese_ci    |      3 |
| sjis     | Shift-JIS Japanese          | sjis_japanese_ci    |      2 |
| hebrew   | ISO 8859-8 Hebrew           | hebrew_general_ci   |      1 |
| tis620   | TIS620 Thai                 | tis620_thai_ci      |      1 |
| euckr    | EUC-KR Korean               | euckr_korean_ci     |      2 |
| koi8u    | KOI8-U Ukrainian            | koi8u_general_ci    |      1 |
| gb2312   | GB2312 Simplified Chinese   | gb2312_chinese_ci   |      2 |
| greek    | ISO 8859-7 Greek            | greek_general_ci    |      1 |
| cp1250   | Windows Central European    | cp1250_general_ci   |      1 |
| gbk      | GBK Simplified Chinese      | gbk_chinese_ci      |      2 |
| latin5   | ISO 8859-9 Turkish          | latin5_turkish_ci   |      1 |
| armscii8 | ARMSCII-8 Armenian          | armscii8_general_ci |      1 |
| utf8     | UTF-8 Unicode               | utf8_general_ci     |      3 |
| ucs2     | UCS-2 Unicode               | ucs2_general_ci     |      2 |
| cp866    | DOS Russian                 | cp866_general_ci    |      1 |
| keybcs2  | DOS Kamenicky Czech-Slovak  | keybcs2_general_ci  |      1 |
| macce    | Mac Central European        | macce_general_ci    |      1 |
| macroman | Mac West European           | macroman_general_ci |      1 |
| cp852    | DOS Central European        | cp852_general_ci    |      1 |
| latin7   | ISO 8859-13 Baltic          | latin7_general_ci   |      1 |
| utf8mb4  | UTF-8 Unicode               | utf8mb4_general_ci  |      4 |
| cp1251   | Windows Cyrillic            | cp1251_general_ci   |      1 |
| utf16    | UTF-16 Unicode              | utf16_general_ci    |      4 |
| utf16le  | UTF-16LE Unicode            | utf16le_general_ci  |      4 |
| cp1256   | Windows Arabic              | cp1256_general_ci   |      1 |
| cp1257   | Windows Baltic              | cp1257_general_ci   |      1 |
| utf32    | UTF-32 Unicode              | utf32_general_ci    |      4 |
| binary   | Binary pseudo charset       | binary              |      1 |
| geostd8  | GEOSTD8 Georgian            | geostd8_general_ci  |      1 |
| cp932    | SJIS for Windows Japanese   | cp932_japanese_ci   |      2 |
| eucjpms  | UJIS for Windows Japanese   | eucjpms_japanese_ci |      3 |
+----------+-----------------------------+---------------------+--------+
40 rows in set (0.00 sec)
#查看排序规则
mysql> show collation;
+--------------------------+----------+-----+---------+----------+---------+
| Collation                | Charset  | Id  | Default | Compiled | Sortlen |
+--------------------------+----------+-----+---------+----------+---------+
| big5_chinese_ci          | big5     |   1 | Yes     | Yes      |       1 |
| big5_bin                 | big5     |  84 |         | Yes      |       1 |
| dec8_swedish_ci          | dec8     |   3 | Yes     | Yes      |       1 |
| dec8_bin                 | dec8     |  69 |         | Yes      |       1 |
| cp850_general_ci         | cp850    |   4 | Yes     | Yes      |       1 |
| cp850_bin                | cp850    |  80 |         | Yes      |       1 |
| hp8_english_ci           | hp8      |   6 | Yes     | Yes      |       1 |
| hp8_bin                  | hp8      |  72 |         | Yes      |       1 |
| koi8r_general_ci         | koi8r    |   7 | Yes     | Yes      |       1 |
| koi8r_bin                | koi8r    |  74 |         | Yes      |       1 |
| latin1_german1_ci        | latin1   |   5 |         | Yes      |       1 |
| latin1_swedish_ci        | latin1   |   8 | Yes     | Yes      |       1 |
| latin1_danish_ci         | latin1   |  15 |         | Yes      |       1 |
| latin1_german2_ci        | latin1   |  31 |         | Yes      |       2 |
| latin1_bin               | latin1   |  47 |         | Yes      |       1 |
| latin1_general_ci        | latin1   |  48 |         | Yes      |       1 |
#查看服务器字符集设置
mysql> show variables like '%character%';
+--------------------------+---------------------------------------------------------------+
| Variable_name            | Value                                                         |
+--------------------------+---------------------------------------------------------------+
| character_set_client     | utf8                                                          |
| character_set_connection | utf8                                                          |
| character_set_database   | utf8                                                          |
| character_set_filesystem | binary                                                        |
| character_set_results    | utf8                                                          |
| character_set_server     | latin1                                                        |
| character_set_system     | utf8                                                          |
| character_sets_dir       | /usr/local/mysql-5.6.10-linux-glibc2.5-x86_64/share/charsets/ |
+--------------------------+---------------------------------------------------------------+
8 rows in set (0.00 sec)

SQL模型(数据违反规定时,SQL的处理方式)

  1. ANSI QUOTES–双引号当单引号使用
  2. IGNORE_SPACE–忽略空白字符
  3. STRICT_ALL_TABLES–没有设置此项时,非法数据被允许,设置此项,违反数据规则的,则全部被拒绝,并抛出错误
  4. STRICT_TRANS_TABLES–不允许向支持事务的表中插入非法数据,并返回错误
  5. TRADITIONAL
#查看sql_mode
mysql> show global variables like 'sql_mode';
+---------------+------------------------+
| Variable_name | Value                  |
+---------------+------------------------+
| sql_mode      | NO_ENGINE_SUBSTITUTION |
+---------------+------------------------+
1 row in set (0.00 sec)

MySQL服务器变量

  • 作用域
    全局变量
    查看全局变量show global variables
    只有root用户可以修改
    会话变量
    查看会话变量show [session] variables
    所有用户可以修改
  • 生效时间
    可动态调整:不用重启服务器生效,即时调整,即时生效
    静态:重启服务器生效,必须写入到配置文件,通过参数传递给mysqld
  • 动态调整参数生效方式
    全局:对当前会话无效,只对新建立的会话有效
    会话:即时生效,只对当前会话有效
    服务器变量:使用select @@查看变量
mysql> select @@global.sql_mode;
+------------------------+
| @@global.sql_mode      |
+------------------------+
| NO_ENGINE_SUBSTITUTION |
+------------------------+
1 row in set (0.00 sec)

设定变量值
SET GLOBAL|SESSION 变量名=值

mysql> set global sql_mode='strict_all_tables';
Query OK, 0 rows affected (0.00 sec)

SQL语句

#创建数据库语法
CREATE DATABASE|schema [IF NOT EXISTS] DB_NAME [CHARSET SET=charset name][collation=collation name]
#创建students数据库
mysql> create database if not exists students character set 'gbk' collate 'gbk_chinese_ci';
Query OK, 1 row affected (0.23 sec)
#查看字符集和排序规则
[root@mail students]# cat db.opt
default-character-set=gbk
default-collation=gbk_chinese_ci
#删除数据库
DROP {DATABASE | SCHEMA} [IF EXISTS] db_name

创建表

  1. 直接定义一张空表
  2. 从其它表中查询出数据,并以之创建新表
  3. 以其它表为模板创建一张空表
CREATE TABLE [IF NOT EXISTS] tb_name (col_name col_definition,constraint) ENGINE [=] engine_name collate [=]collate_name comment[=]comment_name row_format

#创建表
mysql> create table tb1(id int unsigned not null auto_increment primary key,name char(20) not null,age tinyint not null);
Query OK, 0 rows affected (0.24 sec)

mysql> create table tb2(id int unsigned not null auto_increment,name char(20) not null,age tinyint not null,primary key(id));
Query OK, 0 rows affected (0.01 sec)
mysql> create table courses(cid tinyint unsigned not null auto_increment primary key,course varchar(50) not null);
Query OK, 0 rows affected (0.00 sec)
mysql> show table status like 'courses'\\G;
*************************** 1. row ***************************
           Name: courses
         Engine: InnoDB
        Version: 10
     Row_format: Compact
           Rows: 0
 Avg_row_length: 0
    Data_length: 16384
Max_data_length: 0
   Index_length: 0
      Data_free: 0
 Auto_increment: 1
    Create_time: 2021-06-22 05:26:55
    Update_time: NULL
     Check_time: NULL
      Collation: gbk_chinese_ci
       Checksum: NULL
 Create_options: 
        Comment: 
1 row in set (0.00 sec)
#创建表时修改engine为MyISAM
mysql> create table courses(cid tinyint unsigned not null auto_increment primary key,course varchar(50) not null) engine=myisam;
Query OK, 0 rows affected (0.00 sec)

mysql> show table status like 'courses'\\G;
*************************** 1. row ***************************
           Name: courses
         Engine: MyISAM
        Version: 10
     Row_format: Dynamic
           Rows: 0
 Avg_row_length: 0
    Data_length: 0
Max_data_length: 281474976710655
   Index_length: 1024
      Data_free: 0
 Auto_increment: 1
    Create_time: 2021-06-22 05:28:26
    Update_time: 2021-06-22 05:28:26
     Check_time: NULL
      Collation: gbk_chinese_ci
       Checksum: NULL
 Create_options: 
        Comment: 
1 row in set (0.00 sec)
#插入数据
mysql> insert into courses(course) values('Hamogong'),('Pixijianfa'),('kuihuabaodian');
Query OK, 3 rows affected (0.00 sec)
Records: 3  Duplicates: 0  Warnings: 0
#显示表索引
mysql> show indexes from courses;
+---------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| Table   | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment |
+---------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| courses |          0 | PRIMARY  |            1 | cid         | A         |           3 |     NULL | NULL   |      | BTREE      |         |               |
+---------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
1 row in set (0.00 sec)
#通过查询的数据结果,将查询结果创建一张表,并将查询到的数据复制到新表
mysql> create table testcourses select * from courses where cid<=2;
Query OK, 2 rows affected (0.00 sec)
Records: 2  Duplicates: 0  Warnings: 0

mysql> select * from testcourses;
+-----+------------+
| cid | course     |
+-----+------------+
|   1 | Hamogong   |
|   2 | Pixijianfa |
+-----+------------+
2 rows in set (0.00 sec)
#创建一张表类似于courses
mysql> create table test like courses;
Query OK, 0 rows affected (0.00 sec)

mysql> desc test;
+--------+---------------------+------+-----+---------+----------------+
| Field  | Type                | Null | Key | Default | Extra          |
+--------+---------------------+------+-----+---------+----------------+
| cid    | tinyint(3) unsigned | NO   | PRI | NULL    | auto_increment |
| course | varchar(50)         | NO   |     | NULL    |                |
+--------+---------------------+------+-----+---------+----------------+
2 rows in set (0.00 sec)

mysql> desc courses;
+--------+---------------------+------+-----+---------+----------------+
| Field  | Type                | Null | Key | Default | Extra          |
+--------+---------------------+------+-----+---------+----------------+
| cid    | tinyint(3) unsigned | NO   | PRI | NULL    | auto_increment |
| course | varchar(50)         | NO   |     | NULL    |                |
+--------+---------------------+------+-----+---------+----------------+
2 rows in set (0.00 sec)

修改表定义:
ALTER TABLE
添加、删除、修改字段
添加、删除、修改索引
改表名
修改表属性

# 添加唯一键索引
mysql> desc test;
+--------+---------------------+------+-----+---------+----------------+
| Field  | Type                | Null | Key | Default | Extra          |
+--------+---------------------+------+-----+---------+----------------+
| cid    | tinyint(3) unsigned | NO   | PRI | NULL    | auto_increment |
| course | varchar(50)         | NO   |     | NULL    |                |
+--------+---------------------+------+-----+---------+----------------+
2 rows in set (0.00 sec)

mysql> alter table test add unique key(course);
Query OK, 0 rows affected (0.00 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> desc test;
+--------+---------------------+------+-----+---------+----------------+
| Field  | Type                | Null | Key | Default | Extra          |
+--------+---------------------+------+-----+---------+----------------+
| cid    | tinyint(3) unsigned | NO   | PRI | NULL    | auto_increment |
| course | varchar(50)         | NO   | UNI | NULL    |                |
+--------+---------------------+------+-----+---------+----------------+
2 rows in set (0.00 sec)
#修改表字段
mysql> desc test;
+--------+---------------------+------+-----+---------+----------------+
| Field  | Type                | Null | Key | Default | Extra          |
+--------+---------------------+------+-----+---------+----------------+
| cid    | tinyint(3) unsigned | NO   | PRI | NULL    | auto_increment |
| course | varchar(50)         | NO   | UNI | NULL    |                |
+--------+---------------------+------+-----+---------+----------------+
2 rows in set (0.00 sec)

mysql> alter table test change course courses varchar(50) not null;
Query OK, 0 rows affected (0.00 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> desc test;
+---------+---------------------+------+-----+---------+----------------+
| Field   | Type                | Null | Key | Default | Extra          |
+---------+---------------------+------+-----+---------+----------------+
| cid     | tinyint(3) unsigned | NO   | PRI | NULL    | auto_increment |
| courses | varchar(50)         | NO   | UNI | NULL    |                |
+---------+---------------------+------+-----+---------+----------------+
2 rows in set (0.00 sec)
#添加新字段
mysql> desc test;
+---------+---------------------+------+-----+---------+----------------+
| Field   | Type                | Null | Key | Default | Extra          |
+---------+---------------------+------+-----+---------+----------------+
| cid     | tinyint(3) unsigned | NO   | PRI | NULL    | auto_increment |
| courses | varchar(50)         | NO   | UNI | NULL    |                |
+---------+---------------------+------+-----+---------+----------------+
2 rows in set (0.00 sec)

mysql> alter table test add starttime date default '2021-06-21';
Query OK, 0 rows affected (0.00 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> desc test;
+-----------+---------------------+------+-----+------------+----------------+
| Field     | Type                | Null | Key | Default    | Extra          |
+-----------+---------------------+------+-----+------------+----------------+
| cid       | tinyint(3) unsigned | NO   | PRI | NULL       | auto_increment |
| courses   | varchar(50)         | NO   | UNI | NULL       |                |
| starttime | date                | YES  |     | 2021-06-21 |                |
+-----------+---------------------+------+-----+------------+----------------+
3 rows in set (0.00 sec)

#修改数据库表名
mysql> alter table test rename to testcourse;
Query OK, 0 rows affected (0.00 sec)

mysql> show tables;
+--------------------+
| Tables_in_students |
+--------------------+
| courses            |
| testcourse         |
+--------------------+
2 rows in set (0.00 sec)

删除表
DROP [TEMPORARY] TABLE [IF EXISTS]
tbl_name [, tbl_name] …
[RESTRICT | CASCADE]

mysql> create table student(sid int unsigned not null auto_increment primary key,name varchar(30),cid int not null);
Query OK, 0 rows affected (0.00 sec)

mysql> insert into student(name,cid) values('Yue Buqun',2),('Zhang Wuji',1);
Query OK, 2 rows affected (0.00 sec)
Records: 2  Duplicates: 0  Warnings: 0

mysql> select * from student;
+-----+------------+-----+
| sid | name       | cid |
+-----+------------+-----+
|   1 | Yue Buqun  |   2 |
|   2 | Zhang Wuji |   1 |
+-----+------------+-----+
2 rows in set (0.00 sec)

mysql> select * from courses;
+-----+---------------+
| cid | course        |
+-----+---------------+
|   1 | Hamogong      |
|   2 | Pixijianfa    |
|   3 | kuihuabaodian |
+-----+---------------+
mysql> select Name,course from student,courses where student.cid=courses.cid;
+------------+------------+
| Name       | course     |
+------------+------------+
| Yue Buqun  | Pixijianfa |
| Zhang Wuji | Hamogong   |
+------------+------------+
#如果表没有设置外键,则可以插入没有的数据
mysql> insert into student (name,cid) values ('Cheng Jialuo',5);
Query OK, 1 row affected (0.00 sec)

mysql> select * from student;
+-----+--------------+-----+
| sid | name         | cid |
+-----+--------------+-----+
|   1 | Yue Buqun    |   2 |
|   2 | Zhang Wuji   |   1 |
|   3 | Cheng Jialuo |   5 |
+-----+--------------+-----+
3 rows in set (0.00 sec)
mysql> delete from student where cid='5';
Query OK, 1 row affected (0.00 sec)

#给student表添加外键,两个表中的字段类型必须一致,表存储引擎必须支持事务
mysql> alter table student add foreign key(cid) references courses(cid);
Query OK, 2 rows affected (0.23 sec)
Records: 2  Duplicates: 0  Warnings: 0
#查看表索引
mysql> show indexes from student;
+---------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| Table   | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment |
+---------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| student |          0 | PRIMARY  |            1 | sid         | A         |           2 |     NULL | NULL   |      | BTREE      |         |               |
| student |          1 | cid      |            1 | cid         | A         |           2 |     NULL | NULL   |      | BTREE      |         |               |
+---------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
2 rows in set (0.00 sec)
mysql> select * from courses;
+-----+---------------+
| cid | course        |
+-----+---------------+
|   1 | Hamogong      |
|   2 | Pixijianfa    |
|   3 | kuihuabaodian |
+-----+---------------+
3 rows in set (0.00 sec)
#如果插入的数据,关联的外键没有,则会出现报错
mysql> insert into student(name,cid)values('Chen Jialuo',5);
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`students`.`student`, CONSTRAINT `student_ibfk_1` FOREIGN KEY (`cid`) REFERENCES `courses` (`cid`))
#如果数据被其它表中引用,则不能进行删除
mysql> delete from courses where cid ='2';
ERROR 1451 (23000): Cannot delete or update a parent row: a foreign key constraint fails (`students`.`student`, CONSTRAINT `student_ibfk_1` FOREIGN KEY (`cid`) REFERENCES `courses` (`cid`)

#创建索引
mysql> create index name_no_student on student(name) using btree;
Query OK, 0 rows affected (0.03 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> show indexes from student;
+---------+------------+-----------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| Table   | Non_unique | Key_name        | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment |
+---------+------------+-----------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| student |          0 | PRIMARY         |            1 | sid         | A         |           2 |     NULL | NULL   |      | BTREE      |         |               |
| student |          1 | cid             |            1 | cid         | A         |           2 |     NULL | NULL   |      | BTREE      |         |               |
| student |          1 | name_no_student |            1 | name        | A         |           2 |     NULL | NULL   | YES  | BTREE      |         |               |
+---------+------------+-----------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
3 rows in set (0.00 sec)
#删除索引
mysql> drop index name_no_student on student;
Query OK, 0 rows affected (0.00 sec)
Records: 0  Duplicates: 0  Warnings: 0

以上是关于Linux学习-MySQL之SQL语句的主要内容,如果未能解决你的问题,请参考以下文章

Linux学习-MySQL之SQL语句

Linux学习-MySQL之用户管理

Mybatis 学习笔记总结

Linux学习-SQL之SQL语句

Linux命令:MySQL系列之三--mysql数据类型及SQL结构化查询语句使用

python学习44——数据库之MySQL安装与sql语句基础