Home  >  Article  >  Database  >  Summary of common MySQL statements

Summary of common MySQL statements

巴扎黑
巴扎黑Original
2017-07-17 09:51:561563browse

Common database operations

  • ## mysql -u+username -p+password: Log in to the database management system, such as mysql -uroot -p123.

  • create database dbName: Create a database.

  • drop database dbName: Delete the database.

  • use dbName: Use the specified database, because there may be multiple databases in the database management system, use the specified database by name.

  • show databases: Display all databases in the database management system.

  • select database(): Display the database in use.

  • set character_set_results=gbk: Many databases do not support Chinese. Set the encoding method so that Chinese can be displayed normally. It is mainly used to solve the problem of displaying query results in a DOS window. The problem of Chinese garbled characters.

  • source+path (.sql file path): Import the database file and generate the database, that is, generate the database according to the sql script.

  • mysqldump mydatabase>Save directory -uroot -p123: Save all the information of the database to the .sql script file on the hard disk. Since the user name and Password, so operate without entering the database (no semicolon at the end of the statement).

  • create user username identified by 'password': Create a user with a specified name and password, allowing the user to access the database.

  • drop user username "%": Delete the user.

Common operations on the second table

  • ## create table tableName(columnName type(length)) :Create database.

  • drop table tableName: Delete the database.

  • alter table tableName add XXXX: Add fields to the database.

  • alter table tableName drop columnName: Delete a field.

  • alter table tableName change oldName newName XXXX: Overwrite fields.

  • alter table tableName modify columnName XXXX: Modify field attributes.

  • create table copyTable as select columnName/* from oldTable: Copy the table. You can copy all fields or some fields.

  • mysqldump mydatabase mytable>Save directory-uroot -p123: .sql script that saves all the information in a table in the database to the hard disk

    file, note: the database and table are separated by semicolons, forming two characters, one representing the database and one representing the table in the database. If you use "." to connect, it will be As a character, that is, a database, because there is no database with this name in the system, an error occurs during runtime.

  • select@@identity: Get the id of the data just inserted.

Three SQL language classifications

1.DDL

Data Definition Language, data definition language, create/alter/drop.

create: used to create databases and tables.
alter: used to modify the table.

  • alter table tbName add XXXX: Add fields to the table, or add constraints to the fields.

  • alter table tbName mofify XXXX: Modify fields.

  • alter table tbName drop XXXX: Delete a field or constraint.

drop: used to delete databases, tables, fields, and field constraints.

2.DML

Data Manipulation Language, data manipulation language, update/delete/insert.

3.DQL

Data Query Language, data query language, select.

4.TCL

Transaction Control Language, transaction control language, commit/rollback.

5.DCL

Data Control Language, data control language, controls access to the database, grant/revoke.

Four DQL statements constitute

select columnName from tbName where 过滤条件 group by 分组字段 having 分组后过滤条件 order by 排序字段 limit;

1. Execution sequence

from——where——group by——having——select——order by ——limit
  1. from: Enter table .

  2. #where: Filter the data obtained directly from the database, that is, the original data.

  3. group by: followed by the field used for grouping, which can be a single field or a combined field. After grouping, each group of data is processed separately, "select grouping field, grouping processing function", select and add other fields, it will be randomly generated and meaningless;

  4. having: Filtering grouped groups, retaining or deleting certain groups, is not processing the data within the group, so only the field returned by the grouping function can be used in the filtering conditions, a field that can reflect the characteristics of the group.

  5. select: Get data.

  6. order by: sort, asc ascending order, desc descending order. There can be multiple sorting fields. Sort by the previous field first, and then by the following field.

  7. limit: intercept query results, limit n--data from 0 to n, excluding the nth item; limit begin, length--from the specified The starting point intercepts data of a specified length, often used for paging.

2. The difference between where and having

where is used to filter the original data obtained from the database before grouping , the result is to delete some rows and retain some rows, which is a row-specific operation; having is used to filter the groups after grouping, and the result is to delete some groups and retain some groups, which is a group-specific operation.

3.Rename

select oldName (as) newName from table;

对查询结果中的字段重新命名,操作查询结果必须使用新的名称,不改变数据库中的名称。
 

4.自增自减

sql支持在现有字段值基础上进行操作自增自减操作,如 update tb_xxx set count=count+5 。

五 条件查询

用在where语句中,对从数据库获得的原始数据进行过滤。

  •  =:等于,可用于任何数据类型。

  •  <:大于。

  • >:小于。

  •  !=:不等于,另一种方式<>。

  •  is null:为null。

  •  is not null:非空。

  •  and:并且,同时满足两个条件,and的优先级高于or,在两者同时存在的情况下先执行and。

  •  or:或者,满足其中一个条件即可。

  •  between A and B:取值在某个连续区间内,A<=B。

  • in(list01,list02,...):取值在某个数据量有限的列表中。

  • not in(list01,list02):取值不在某个数据量有限的列表中。

  • like:模糊查询,%代表0-n个字符,_代表一个字符,查找符合指定模板的字符。

六 数据处理函数

数据处理函数又叫做单行处理函数,用来处理单行数据,字段名作为方法的参数。

  • Lower():将查询结果全部转化为小写。

  • Upper():将查询结构全部转化为大写。

  • trim():去除前导与后导空格。

  • substr(columnName,begin,length):截取查询结果的一部分。

  • round():四舍五入。

  • rand():生成随机数。

  • ifnull(columnName,defaultValue):如果查询得到的数据为null,则赋一个默认值。

七 分组函数

分组函数又叫做多行处理行数,按照分组字段,对每一组数据分别进行处理,每组数据输出一条结果。分组行数自动忽略null。
分组函数不能使用在where子句中,如 select xxx from xxx where xxx>sum(xxx),因为分组函数只能在分组后使用。

  •  sum():求和。

  •  max():求最大值。

  •  min():求最小值。

  •  avg():求平均值。

  •  count():获得记录总数,count(*)获得包括null在内的全部记录数,count(columnName)获得指定字段非null记录数。

八 其他关键字

1.distinct

select distinct columnName01,columnName02 from table;

去除重复指定字段的重复记录,既可以是单个字段,也可以是组合字段。distinct前面不可以出现任何字段,因为前面字段的数据全部取出,后面的字段去除了重复记录,导致两个字段记录数不相等,产生冲突。

2.union

select columnName01,...from tbName01 union select columnName02,...from tbName02;

合并结果集,将两次分别查询的结果合并为一个结果,把后面字段的查询结果追加到前面对应位置字段的查询结果后面。

  • 前后查询字段的个数必须相同,无法合并。

  • 当前后对应位置的两个字段名称不同时,合并后的结果采用前面的字段名。

九 日期处理函数

1.通用性

由于不同数据库处理日期的方式不一样,为了提高数据的适用性,数据库在存储日期时通常采用字符串形式。

2.字符串转化为日期

str_to_date(字符串,格式);

如果底层日期储存采用的是date类型,而输入的是字符串,那么在将数据存储到数据库前需要将字符串转化为date类型,而这一操作只是告诉系统将字符串转化为date类型数据,并不能改变数据库底层的储存样式。
date类型数据在数据库统一采用"%Y-%d-%m %H-%i-%s"的存储。

 3.日期转化为字符串

date_format(日期字段,格式):

如果数据底层采用日期存储格式,那么在获取日期以后可以改变查询结果集中日期的格式。

4.默认格式

"%Y-%d-%m %H-%i-%s"

MySQL中date类型数据的默认格式,如果字符串符合该格式,插入或者查询时被自动转化为date类型。

5.日期对比

在SQL语句中,采用关系运算符><=比较日期类型数据。

十 表连接

1.背景

理论上将全部数据放到同一张表中很难实现,实际上即使实现了,表也很庞大,很冗杂,不便于查询与维护,因此将不同的数据存放到不同的表中,需要时连接各表进行查询。

2.连接条件

两张表连接时,将其中一张表中的每行数据与另外一张表的全部数据进行对比,如果满足给定的条件,则将这两行数据合并为一行,否则舍弃,继续对比剩余行。

3.笛卡尔现象

如果表连接时未设置连接条件,那么返回的查询结果数目是两张表行数的乘积,这种现象被叫做笛卡尔现象。

4.连接的几种方式

⑴内连接

select t1.columnName01,t2.columnName02 from tbName01 t1(inner)join tbName02 t2 on 连接条件;
  • 两张表进行连接查询,如果只显示匹配数据,那么采用内连接的方式。

  • 为了指明字段所属的表,为每一张参与连接的表指定别名,通过别名调用其中的字段。

 ⑵外连接

select t1.columnName01,t2.columnName02 from tbName01 t1 right/left (outer) join tbName02 t2 on 连接条件;

外连接将连接指向的一张表中的数据全部返回,另一种表对应字段无匹配数据时用null填充。在外连接中使用left,左边表的数据被全部取出;使用right,右边表的数据被全部取出。

5.多张表连接查询

一张表A与多张表连接查询,表A与其他表分别进行连接,最终的结果是各个独立连接查询结果相同A表数据的组合,即将某一个连接查询结果中的某一行A表字段全部取出,如果其他连接查询结果都具有该A字段,则所有具有该字段的行合并为一行。
 

6.别名

表连接查询时通常通过表的别名来引用字段,如果某个字段只出现在一张表中可以省略别名。

十一 约束

 1.约束类型

数据库可以添加的约束有非空约束(not null)、唯一性约束(unique)、主键约束(primary key)、    外键约束(foreign key)。

2.unique

unique约束用来约束一个字段不能有重复数据,允许多行数据同时为null。

多个字段可以联合起来添加unique约束,只有在多个字段对应数据均相同的情况下,才认为是重复数据。

create tabletableName(columnName01,columnName02,unique(columnName01, columnName02));

3.primary key

数据库中的重复数据不仅对实际应用没有意义,反而占用系统资源,使数据库冗杂,操作缓慢,为了避免重复数据 的出现,为表中的每一个行数据均设置一个唯一性标识,这个标识就是primary key。被设定为priamry key的字段 不仅不可以为null,而且不可以重复,但不等于同时设置了not null与unique,因为还为该字段添加了索引index。

主键字段的创建

create table tableName(id int(1) primary key auto_increment);
  • 其中auto_increment为是主键的生成 策略,表示主键的值自动生成。

  • MySQL并未实现主键生成策略sequence,可以借助Hibernate框架实现。

  • 一张表中只能存在一个唯一性标识,即只能有一个主键。 

  • 按照取值性质不同,主键可以分为: 1.自然主键:主键值是自然数,主键与当前业务无关,同一行中其他数据的改变不会导致主键值的改变。 2.业务主键:主键值与业务相关,同一行中其他数据的改变可能导致主键的改变,一般主键不推荐设置成这种方式。

  • 主键可以由一个字段构成,也可以由多个字段联合构成。在采用联合主键的情况下,可能出现非主键字段对主键 字段的部分依赖,产生数据冗杂,违法数据库设计第二范式,因此谨慎使用联合主键。

4.foreign key    

⑴背景

如果一张表A的某个字段引用另一张表B中的某个字段,为了保证引用的正确,在A表中添加外键。

⑵外键字段的创建

create table tbName(id (1) primary key auto_increment,name varchar(10) not ,classNo (1),foreign key(classNo) 
references 父表(父表中被引用字段));
  • 在表创建完成以后,可以为表中字段添加约束:alter table tbName add 约束定义形式。

  • 一张表可以有多个外键字段,外键字段可以为null。

  • 父表中被引用字段数据不能重复,必须有unique约束。

⑶级联操作

为了保证子表中的数据跟随父表的变化而变化,可以为外键添加级联操作。
级联关系是父表控制子表,使子表发生同样的变化,不是子表控制父表,子表的变化不影响父表。不设置级联操作时,父表被引用字段被引用数据不能更改,外键字段可以更改为父表中主键字段的其他值。
级联更新:

create table tbName(id (1) primary key auto_increment,name varchar(10) not (1),foreign key(classNo) 
references 父表(父表中被引用字段)on update cascade);

当父表中的数据更新时,子表中的数据做出同样的更新。
级联删除:

create table tbName(id (1) primary key auto_increment,name varchar(10) not (1),foreign key(classNo) 
references 父表(父表中被引用字段)on delete cascade);

当父表中的数据被删除时,子表中对应的数据也同样被删除。
同时为外键设置级联更新与级联删除:

create table tbName(id (1) primary key auto_increment,name varchar(10) not (1

⑷删除顺序

由于子表依赖于父表,创建时先创建父表,删除时先删除子表。

⑸一对多关联关系

典型的一对多关系,在多的一方添加外键,即A表中的多行数据对应B表中的一行数据,那么在A表中添加外键,引用B表中的数据。

⑹约束名

可以使用“constraint name +约束定义形式”的格式,在表创建添加约束的同时,为约束设定名称,以便后续操作。

⑺外部定义

在表定义外部,通过约束名称删除约束:

alter table tbName drop foreign key name;

⑻外键使用限制

设置外键后,需要同时维护两张表,增加了数据库负担,降低了性能,因此尽量避免使用外键。

十二 索引

1.未使用索引时表的检索方式?全盘检索。

2.什么是索引?

  • 索引是一种提高查询效率的策略,对应于一个文件,文件中保存了索引字段排序后的信息以及其他信息。

  • 索引相当于一本书的目录,可以快速定位到一列数据中具有特定值的行。

3.索引适用的条件

  • 数据量较大。

  • 数据很少被DML语句操作,因为索引字段发生改变,索引文件需要更新,降低了表的更新速度。

  • 索引字段经常出现在where语句中。

4.可以为一张表中的多个字段添加索引,多个索引有主次之分。

5.创建索引

create index indexName on tableName(columnName);

6.删除索引

drop index indexName on tableName;

7.索引的创建与删除格式不同与约束的格式,因为索引与约束是不同类型的属性。

十三 事务

1.什么是事务?

不可再分割的工作单元,保证多个DML语句同时有效或者同时无效。

2.事务操作基于内存

事务基于内存中的数据进行操作,每一步操作都会被保存到内存中,提交时将内存中的操作结果同步到数据库,并且清空内存;回滚时删除内存中的操作。在事务提交前,事务内部的每一步操作都会基于内存中的数据被执行,而不是在事务提交的一刻才全部执行,而是在事务提交前分步执行,事务提交时将执行结果写入数据库。可以概括为事务基于内存,分步执行。

3.特性(ACID)

  • A原子性:事务是一个最小的单元,不可再分。

  • C一致性:事务中的所有操作或者全部起作用,或者全部失效,不存在部分起作用,部分不起作用的情况。

  • I隔离性:事务之间相互隔离,彼此相互独立。

  • D持久性:事务对数据库的操作会反映到数据库中。

4.关闭自动提交

MySQL在默认情况下自动提交事务,即每执行一句DML语句,就会同步到数据库,关闭自动提交的两种方式:

start transaction-- DML---commit,或者start transaction--DML--rollback;
set autocommit=off(on);

以上两种方式只对当前会话有效。

5.隔离级别

  • read uncommitted:一个事务可以读取另一个事务未提交的数据,这个数据被称为脏数据。

  • read committed:其他事务频繁地提交数据,另个事务(时间跨度大)在未提交之前多次读取提交的数据,可能出现多次读取的数据不一致。

  • repeatable read:事务首次从数据库中读取数据,然后将数据保存在内存中,以后不是从数据库,而是从内存中读取数据。这种隔离级别可能导致读取的数据与数据库中数据不一致,出现“幻想”。

  • serializable:一个事务操作完数据以后,其他事务才可以操作。

6设置隔离级别

  • set global transaction isolation level XXXX:对所用会话有效。

  • set session transaction isolation level XXXX:只对当前会话有效。

7.查看隔离级别

  • select@@tx_isolation: 查看当前会话的隔离级别,另一种方式 select@@session.tx_isolation。

  • select@@global.tx_isolation: 查看全局的事务隔离级别。

十四 行级锁

1.什么是行级锁?

行级锁是一个数据库事务隔离方面的概念,为查询到的数据加锁,当前事务提交之前,不允许其他事务访问锁定的数据。

2.行级锁实现

select ...for update;

在一般的DQL语句结尾添加“for update”,DQL语句查询的字段就被锁,然后再在事务内部对锁定的数据进行其他操作。

3.数据库线程安全问题的几种解决方案

  1. java方面:为操作数据库的代码添加synchronized同步机制。

  2. 事务方面:serializable串行化。

  3. SQL语句方面:行级锁。

十五 视图View

1.什么是视图?

视图相当于表的一个副本,是表隐藏了部分数据与实现细节的结果,提供了一种比较安全的操作数据的方式。

2.创建

create view 视图名 as select columnName01 as newName01,columnName02,...from tbName;

3.同步

视图具有与表相同的属性与操作,两者绑定,对一个的操作也是对另一个的操作;

十六 SQL注入

1.什么是SQL注入?

攻击者将SQL语句通过表单输入或者请求地址中的请求参数注入到服务器中,执行恶意的SQL命令,如select * from table where name='name01'and password='n'or'a'='a';

2.SQL发生的根本原因

编译时把包含SQL关键字的用户输入一同编译,这样SQL语句发生扭曲。

3.防止SQL注入的一种方案

将SQL语句的框架与用户输入的参数分开,先编译框架,然后接收参数,这样就会把含有SQL关键字的输入当做普通字符串了,不会执行恶意的SQL命令。    

十七 存储引擎(MySQL专有)

1.什么是存储引用?

数据库管理系统简化了数据库的创建与维护,但底层依然没有跳过对数据的基础处理,比如将数据存放在什么样的文件中,以什么样的结构存放、怎么访问与修改等问题,存储引擎是数据库管理系统的底层实现,是数据的底层具体存储方式,是一种数据的存储技术。
 2.存储引擎是一个表级概念,可以为同一数据库中不同的表设置不同的存储引擎。

3.分类

⑴InnoDB

MySQL默认的存储引擎,支持事务、外键、行级锁,MySQL程序崩溃后,提供自动恢复,数据及其他信息以.frm文件格式存储;

⑵MyISAM

    底层有3个文件:

  • frm:存放表结构。

  • MYD:存放数据。

  • MYI:存放索引。

特点:

  • 不支持事务。

  • 支持压缩只读表。

  • 该引擎使用了索引,因此适用环境受索引的约束,主要用于数据量较大、数据很少更改的表。

⑶Memory

  • 数据与索引存储在内存中,因此检索速度最快,缺点是无法持久。

  • 以.frm文件格式存储信息。

  • 不支持事务。

 4.显示MySQL支持的引擎

show engines\G:

Eighteen Three Paradigms of Database Design

Basic principles that should be followed when designing a database:

1. There is a primary key, The fields cannot be subdivided

The primary key can not only be used as the unique identifier of the data to avoid data duplication, but also contains an index, which increases the query speed. If a certain field can be further divided, compared with the divided field, the maintenance of this field is inconvenient and the query speed is slow.

2. Non-primary key fields are completely dependent on the primary key and cannot be partially dependent.

This specification is mainly to limit the use of joint primary keys. Only one type of entity information can be stored in a table. When using a joint primary key, Non-primary key fields may only have a dependency on one field of the joint primary key. In detail, assuming that a table uses joint primary keys KA and KB, one of the non-primary key fields C only depends on KB. Since the uniqueness of a row of data is jointly determined by KA and KB, a certain value of KB can If multiple values ​​of KA appear in multiple rows, then in any row where a certain value appears in KB, a certain value C0 of the corresponding field C must also appear, like this C0 appears repeatedly in multiple rows, resulting in cluttered data.

3. Transitive dependencies cannot occur

#A certain non-primary key field C depends on another non-primary key field B, and B completely depends on The primary key field A, then the dependence of C on A is established through the transmission of B, and the dependence of C on A is transitive dependence. If B appears repeatedly, then C appears repeatedly. You shouldcreate another table to store B and C with B as the primary key, and create a foreign key for B in the original table, pointing to the table.

In short, store different objects separately. In actual development, it is not necessary to strictly adhere to the three paradigms, in order to meet the project needs as the highest purpose, sometimes the structure can be sacrificed in pursuit of speed.

The above is the detailed content of Summary of common MySQL statements. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn