Mysql field types, query statements, and advanced operations

Contents of this article:

1. Mysql field types

1. Numeric type

2. Date and time types

3. String type
2. Mysql query method

2-1.Conditional query

2-2. Aggregation query

2-3. Group query

2-4. Sorting query

2-5.Paging query

3.Mysql advanced operations

1. Relationship between tables (foreign keys)

2. Connection query

3. Self-correlation

4. Built-in functions

5. Encapsulate the query statement: view

6. Affairs

7.Mysql paradigm:


For the installation of MySql, please refer to the previous article: http://blog.csdn.net/qq_33613696/article/details/77372666



1. Mysql field types


The types of data fields defined in MySQL are very important for the optimization of your database.
MySQL supports multiple types, which can be roughly divided into three categories: numerical, date/time and string (character) types .


1. Numeric type
MySQL supports all standard SQL numerical data types.
These types include strict numeric data types (INTEGER, SMALLINT, DECIMAL, and NUMERIC), and approximate numeric data types (FLOAT, REAL, and DOUBLE PRECISION).
The keyword INT is a synonym for INTEGER, and the keyword DEC is a synonym for DECIMAL.
The BIT data type stores bit field values ​​and supports MyISAM, MEMORY, InnoDB and BDB tables.
As an extension to the SQL standard, MySQL also supports integer types TINYINT, MEDIUMINT and BIGINT. The following table shows the storage and range required for each integer type.

type

size Range (signed) Range (unsigned) use
TINYINT 1 byte (-128,127) (0,255) small integer value
SMALLINT 2 bytes (-32 768,32 767) (0,65 535) large integer value
MEDIUMINT 3 字节 (-8 388 608,8 388 607) (0,16 777 215) 大整数值
INT或INTEGER 4 字节 (-2 147 483 648,2 147 483 647) (0,4 294 967 295) 大整数值
BIGINT 8 字节 (-9 233 372 036 854 775 808,9 223 372 036 854 775 807) (0,18 446 744 073 709 551 615) 极大整数值
FLOAT 4 字节 (-3.402 823 466 E+38,-1.175 494 351 E-38),0,(1.175 494 351 E-38,3.402 823 466 351 E+38) 0,(1.175 494 351 E-38,3.402 823 466 E+38) 单精度
浮点数值
DOUBLE 8 字节 (-1.797 693 134 862 315 7 E+308,-2.225 073 858 507 201 4 E-308),0,(2.225 073 858 507 201 4 E-308,1.797 693 134 862 315 7 E+308) 0,(2.225 073 858 507 201 4 E-308,1.797 693 134 862 315 7 E+308) 双精度
浮点数值
DECIMAL 对DECIMAL(M,D) ,如果M>D,为M+2否则为D+2 依赖于M和D的值 依赖于M和D的值 小数值


2.日期和时间类型

表示时间值的日期和时间类型为DATETIME、DATE、TIMESTAMP、TIME和YEAR。

每个时间类型有一个有效值范围和一个"零"值,当指定不合法的MySQL不能表示的值时使用"零"值。

TIMESTAMP类型有专有的自动更新特性。

类型 大小
(字节)
范围 格式 用途
DATE 3 1000-01-01/9999-12-31 YYYY-MM-DD 日期值
TIME 3 '-838:59:59'/'838:59:59' HH:MM:SS 时间值或持续时间
YEAR 1 1901/2155 YYYY 年份值
DATETIME 8 1000-01-01 00:00:00/9999-12-31 23:59:59 YYYY-MM-DD HH:MM:SS 混合日期和时间值
TIMESTAMP 4 1970-01-01 00:00:00/2037 年某时 YYYYMMDD HHMMSS 混合日期和时间值,时间戳


3.字符串类型

字符串类型指CHAR、VARCHAR、BINARY、VARBINARY、BLOB、TEXT、ENUM和SET。该节描述了这些类型如何工作以及如何在查询中使用这些类型。

类型 大小 用途
CHAR 0-255字节 定长字符串
VARCHAR 0-65535 字节 变长字符串
TINYBLOB 0-255字节 不超过 255 个字符的二进制字符串
TINYTEXT 0-255字节 短文本字符串
BLOB 0-65 535字节 二进制形式的长文本数据
TEXT 0-65 535字节 长文本数据
MEDIUMBLOB 0-16 777 215字节 二进制形式的中等长度文本数据
MEDIUMTEXT 0-16 777 215字节 中等长度文本数据
LONGBLOB 0-4 294 967 295字节 二进制形式的极大文本数据
LONGTEXT 0-4 294 967 295字节 极大文本数据

CHAR和VARCHAR类型类似,但它们保存和检索的方式不同。它们的最大长度和是否尾部空格被保留等方面也不同。在存储或检索过程中不进行大小写转换。

BINARY和VARBINARY类类似于CHAR和VARCHAR,不同的是它们包含二进制字符串而不要非二进制字符串。也就是说,它们包含字节字符串而不是字符字符串。这说明它们没有字符集,并且排序和比较基于列值字节的数值值。

BLOB是一个二进制大对象,可以容纳可变数量的数据。有4种BLOB类型:TINYBLOB、BLOB、MEDIUMBLOB和LONGBLOB。它们只是可容纳值的最大长度不同。

There are 4 TEXT types: TINYTEXT, TEXT, MEDIUMTEXT and LONGTEXT. These correspond to 4 BLOB types, with the same maximum length and storage requirements.


2. Mysql query method

2-1.Conditional query

2-2. Aggregation query

2-3. Group query

2-4. Sorting query

2-5.Paging query




Basic syntax of query

select * from 表名;

Write the table name after the from keyword, indicating that the data comes from the
column names in the table written after select. If it is *, it means that the
column names of all columns in the table after select are displayed in the result. You can use as to start the column. Alias, this alias appears in the result set

If you want to query multiple columns, use commas to separate them.


Eliminate duplicate rows. Use distinct
before selecting the following column to eliminate duplicate rows. Select distinct gender from students;


2-1. Conditional query:

Use the where clause to filter the data in the table. Rows with a true result will appear in the result set.
The syntax is as follows:

select * from 表名 where 条件;


Comparison operators
equal=
greater than>
greater than or equal>=
less than<
less than or equal<=
not equal to!= or <>


Query students whose number is greater than 3

select * from students where id>3;
Query the subjects whose number is not greater than 4
select * from subjects where id<=4;
Search for students whose name is not "Huang Rong"
select * from students where sname!='黄蓉';
Query students who have not been deleted
select * from students where isdelete=0;

Logical Operators

and
or
not


Query female classmates with numbers greater than 3

select * from students where id>3 and gender=0;
Query students with numbers less than 4 or who have not been deleted
select * from students where id<4 or isdelete=0;

Fuzzy query
like
% represents any number of arbitrary characters_represents
one arbitrary character


Search for students named Huang

select * from students where sname like '黄%';
Search for students whose surname is Huang and whose first name is one character
select * from students where sname like '黄_';
Search for students named Huang or Jing
select * from students where sname like '黄%' or sname like '%靖%';

Range query
in represents a non-continuous range


Query students whose number is 1 or 3 or 8

select * from students where id in(1,3,8);
between ... and ... indicates that in a continuous range,
the query students are students from 3 to 8
select * from students where id between 3 and 8;
Check if the student is a boy from 3 to 8 years old
select * from students where id between 3 and 8 and gender=1;

Null judgment
Note: null and '' are different

Test is null

Judgment is not null


Check for students who have not filled in their address

select * from students where hometown is null;
If it is not null, check
the students who filled in the address.
select * from students where hometown is not null;
Query girls who have filled in their addresses
select * from students where hometown is not null and gender=0;


Priority:
Parentheses, not, comparison operators, logical operators
and are operated before or. If they appear at the same time and you want or to be calculated first, you need to use it in combination with ()

2-2. Aggregation query

In order to quickly obtain statistical data, 5 aggregate functions are provided

count(*) means to calculate the total number of rows, write stars and column names in parentheses, the results are the same.
Query the total number of students

select count(*) from students;


max(column) means to find the maximum value of this column.
Query the maximum number of girls.
select max(id) from students where gender=0;


min(column) means to find the minimum value of this column. To query
the minimum number of undeleted students,
select min(id) from students where isdelete=0;

sum(column) means to find the sum of this column.
After querying the number of boys,
select sum(id) from students where gender=1;

avg(column) means to find the average of this column.
Query the average number of girls who have not been deleted.
select avg(id) from students where isdelete=0 and gender=0;


2-3. Group query

Grouping by field means that data with the same field will be put into a group.
After grouping, only the same data columns can be queried. Different data columns cannot appear in the result set.
You can make statistics on the grouped data. Do Aggregation operation
syntax:

select 列1,列2,聚合... from 表名 group by 列1,列2,列3...

Query the total number of boys and girls
select gender as 性别,count(*)
from students
group by gender;

Check the number of people in each city
select hometown as 家乡,count(*)
from students
group by hometown;


Data filtering after grouping

Syntax:
select 列1,列2,聚合... from 表名
group by 列1,列2,列3...
having 列1,...聚合...

The conditional operator after having is the same as where

Query the total number of boys
Option 1

select count(*)
from students
where gender=1;
-----------------------------------方案二:
select gender as 性别,count(*)
from students
group by gender
having gender=1;

Compare where and having

where is to filter the data in the table specified after from, and
having is to filter the results of group by.


2-4. Sorting query

To facilitate viewing of data, the data can be sorted
. Syntax:

select * from 表名
order by 列1 asc|desc,列2 asc|desc,...

Sort the row data according to column 1. If the values ​​of some rows and rows 1 are the same, they will be sorted according to column 2, and so on. By default, the
column values ​​are sorted from small to large,
asc is sorted from small to large, that is, in ascending order,
desc is sorted from large to small. , that is, descending order


Query the information of male students who have not been deleted, in descending order by student number

select * from students
where gender=1 and isdelete=0
order by id desc;


Query the account information that has not been deleted, sorted by name in ascending order
select * from subject
where isdelete=0
order by stitle;



2-5. Paging query

When the amount of data is too large, it is very troublesome to view the data on one page.


Syntax   limit star, count

select * from 表名 limit start,count


从start开始,获取count条数据
start索引从0开始



三.Mysql高级操作

1.表与表之间的关系(外键)

2.连接查询

3.自关联

4.内置函数

5.对查询语句进行封装:视图

6.事务


1.表与表之间的关系

表与表之间一般存在三种关系,即一对一,一对多,多对多关系。 

一对一关系:使用单表,加字段进行标注

一对多关系:建多表,并且在多的那张表上建立对一的外键(一般为id)进行标注。

多对多关系:另建关系表对关系另行存储

参考:http://blog.csdn.net/lengjinghk/article/details/52140276


外键:简单来说就是一张表中的某非主键的一个字段是其他表中的主键(如id)。

外键一般用来表示表与表之间的关系。

外键还可以进行联级操作,即当外键本身被删除时,也可以删除此外键相关的列

类型包括:
restrict(限制):默认值,抛异常
cascade(级联):如果主表的记录删掉,则从表中相关联的记录都将被删除
set null:将外键设置为空
no action:什么都不做


2.连接查询

连接查询分类如下:


表A inner join 表B:表A与表B匹配的行会出现在结果中
表A left join 表B:表A与表B匹配的行会出现在结果中,外加表A中独有的数据,未对应的数据使用null填充
表A right join 表B:表A与表B匹配的行会出现在结果中,外加表B中独有的数据,未对应的数据使用null填充

在查询或条件中推荐使用“表名.列名”的语法
如果多个表中列名不重复可以省略“表名.”部分
如果表的名称太长,可以在表名后面使用' as 简写名'或' 简写名',为表起个临时的简写名称

查询学生的姓名、平均分
select students.sname,avg(scores.score)
from scores
inner join students on scores.stuid=students.id
group by students.sname;

3.自关联:

设计省信息的表结构provinces
id
ptitle
设计市信息的表结构citys
id
ctitle
proid

citys表的proid表示城市所属的省,对应着provinces表的id值

问题:能不能将两个表合成一张表呢?
思考:观察两张表发现,citys表比provinces表多一个列proid,其它列的类型都是一样的
意义:存储的都是地区信息,而且每种信息的数据量有限,没必要增加一个新表,或者将来还要存储区、乡镇信息,都增加新表的开销太大

答案:定义表areas,结构如下
id
atitle
pid
因为省没有所属的省份,所以可以填写为null
城市所属的省份pid,填写省所对应的编号id


这就是自关联,表中的某一列,关联了这个表中的另外一列,但是它们的业务逻辑含义是不一样的,城市信息的pid引用的是省信息的id
在这个表中,结构不变,可以添加区县、乡镇街道、村社区等信息


4.内置函数

mysql提供了一些内置函数


字符串函数

查看字符的ascii码值ascii(str),str是空串时返回0

select ascii('a');
查看ascii码值对应的字符char(数字)
select char(97);
拼接字符串concat(str1,str2...)
select concat(12,34,'ab');
包含字符个数length(str)
select length('abc');
截取字符串
left(str,len)返回字符串str的左端len个字符
right(str,len)返回字符串str的右端len个字符
substring(str,pos,len)返回字符串str的位置pos起len个字符
select substring('abc123',2,3);
去除空格
ltrim(str)返回删除了左空格的字符串str
rtrim(str)返回删除了右空格的字符串str
trim([方向 remstr from str)返回从某侧删除remstr后的字符串str,方向词包括both、leading、trailing,表示两侧、左、右
select trim('  bar   ');
select trim(leading 'x' FROM 'xxxbarxxx');
select trim(both 'x' FROM 'xxxbarxxx');
select trim(trailing 'x' FROM 'xxxbarxxx');

返回由n个空格字符组成的一个字符串space(n)
select space(10);

替换字符串replace(str,from_str,to_str)
select replace('abc123','123','def');

大小写转换,函数如下
lower(str)
upper(str)
select lower('aBcD');


数学函数

求绝对值abs(n)
select abs(-32);

求m除以n的余数mod(m,n),同运算符%
select mod(10,3);
select 10%3;

地板floor(n),表示不大于n的最大整数
select floor(2.3);

天花板ceiling(n),表示不小于n的最大整数
select ceiling(2.3);

求四舍五入值round(n,d),n表示原数,d表示小数位置,默认为0
select round(1.6);

求x的y次幂pow(x,y)
select pow(2,3);

获取圆周率PI()
select PI();

随机数rand(),值为0-1.0的浮点数
select rand();

还有其它很多三角函数,使用时可以查询文档

日期时间函数

获取子值,语法如下

year(date)返回date的年份(范围在1000到9999)
month(date)返回date中的月份数值
day(date)返回date中的日期数值
hour(time)返回time的小时数(范围是0到23)
minute(time)返回time的分钟数(范围是0到59)
second(time)返回time的秒数(范围是0到59)
select year('2016-12-21');

日期计算,使用+-运算符,数字后面的关键字为year、month、day、hour、minute、second
select '2016-12-21'+interval 1 day;
日期格式化date_format(date,format),format参数可用的值如下

获取年%Y,返回4位的整数
获取年%y,返回2位的整数
获取月%m,值为1-12的整数
获取日%d,返回整数
获取时%H,值为0-23的整数
获取时%h,值为1-12的整数
获取分%i,值为0-59的整数
获取秒%s,值为0-59的整数

select date_format('2016-12-21','%Y %m %d');

当前日期current_date()

select current_date();

当前时间current_time()

select current_time();

当前日期时间now()

select now();


5.对查询语句进行封装:视图

For complex queries, maintenance is a very troublesome thing after multiple uses.
Solution: Define a view.
The essence of a view is an encapsulation of the query.
Define a view.

create view stuscore as 
select students.*,scores.score from scores
inner join students on scores.stuid=students.id;

The purpose of the view is to query
select * from stuscore;


6. Affairs

When a business logic requires multiple SQL statements to be completed, if one of the SQL statements makes an error, you want the entire operation to be returned. You can use transactions to complete the return
function and ensure the correctness of the business logic. The four major characteristics of
transactions (referred to as ACID)
are atomic ( Atomicity) : All operations in a transaction are inseparable in the database, either all are completed, or none are executed.
Consistency : The execution results of several transactions executed in parallel must be the same as those executed serially in a certain order. Consistent results
Isolation (Isolation) : The execution of a transaction is not interfered by other transactions, and the intermediate results of transaction execution must be transparent to other transactions
Durability (Durability) : For any submitted transaction, the system must ensure that the transaction is transparent to the database The changes will not be lost, even if the database fails.
Requirement: The type of the table must be innodb or bdb type before transactions can be used on this table


Transaction statement:

Turn on begin;
submit commit;
rollback rollback;


After the begin transaction is enabled, if you do not commit, no changes will be made to the database. Only if the commit succeeds will real changes be made to the database.

7.Mysql paradigm:


Baidu Encyclopedia explanation: Click to open the link

范式(数据库设计范式,数据库的设计范式)
是符合某一种级别的关系模式的集合。构造数据库必须遵循一定的规则。在关系数据库中,这种规则就是范式。关系数据库中的关系必须满足一定的要求,即满足不同的范式。

目前关系数据库有六种范式:第一范式(1NF)、第二范式(2NF)、第三范式(3NF)、Boyce-Codd范式(BCNF)、第四范式(4NF)和第五范式(5NF)。


满足最低要求的范式是第一范式(1NF)。在第一范式的基础上进一步满足更多要求的称为第二范式(2NF),其余范式以次类推。一般说来,数据库只需满足第三范式(3NF)就行了。


三范式:

第一范式(1NF):列不可拆分
第二范式(2NF):唯一标识
第三范式(3NF):引用主键

说明:后一个范式,都是在前一个范式的基础上建立的




Guess you like

Origin blog.csdn.net/qq_33613696/article/details/77435281