Getting started with SQL
Summary from: PHP from beginner to proficient - including basic introduction, MySQL, project practice, Sun Shengli
Basic concepts of database
- Database: A warehouse for information storage, including a series of relationship measures!
- Table: There can be several tables in a database, and the tables we create in our daily life can be seen in form.
- Field: The information in the table will be stored in several columns. We call these columns "fields" in the database, and the specific information stored in the columns is called "field value".
- Record: We call a piece of information a record
- Several databases can be established in a database management system, and several tables can be established in each database. Each table can have several records.
Data types supported by MySQL
Numeric type
- type
integer type byte range (signed) range (unsigned) TINYINT 1 -128,127 0,255 SMALLINT 2 -32768,32767 0,65535 MEDIUMINT 3 -8388608,8388607 0,16777215 INT,INTEGER 4 -2147483648,2147483647 0,4294967295 BIGINT 8 -9223372036854775808,9223372036854775807 0,18446744073709551615 - zerofill: Display width. When defining the type, specify the display width in parentheses after the type name. For example, int(5) means when the value width is less than 5 digits At this time, the width is filled in front of the number. If the top width is not displayed, the default is int(11). Generally used with zerofill, filled with "0". If you insert a value larger than the width limit, it has no effect and is saved according to the actual precision of the type.
- unsigned: All integer types have an optional attribute unsigned (unsigned). You can use this option if you need to store non-negative numbers in the field or if you need a larger upper limit. If a column is specified as zerofill, MySQL automatically adds the unsigned attribute to the column.
- auto_increment: This attribute can be used when a unique identifier or sequential value needs to be generated. This attribute can only be used for integer types. The auto_increment value generally starts from 1 and increases by 1 for each row. When inserting null into an auto_increment column, MySQL inserts a value that is 1 greater than the current maximum value in the column. There can be at most one auto_increment column in a table. For the auto_increment column, it should be defined as not null, and defined as a primary key or a unique key.
- Primary key: One or more fields that can uniquely identify a record
- Note:
- It is best not to set the primary key on a field related to actual information. The role of the primary key should be clear and single
- The primary key is best set on an integer type field (it is more efficient to process or query)
- The primary key must be different and cannot be null
- Since the primary key It must be different, so we will use the auto_increment attribute
- A table can only have one primary key, it is best to set it on only one field
- Query based on the value of the primary key You can get extremely fast speed when recording (because the field where the primary key is set has already been indexed)! - Setting method:
When creating the table
primary key (field)
primary key (field 1 , field 2)
For example: create table table name (field name 1 type,..., primary key (field name 1));
can also be written directly in After the field where the primary key needs to be created
create table table name (field name type primary key,...);
If you forget to set it, you can alter table table name add primary key (field name); - Delete: alter table table name drop primary key; Note: If the field has the auto_increment attribute, the auto_increment attribute must be deleted first;
- Note:
- not null: Specifies whether the value of the field can be null. Not null means it cannot be null. This attribute can also be used for other types of fields.
- default: Set the default value. This attribute can also be used for other types of fields.
- 例如:create table t10(id int auto_increment primary key, name int not null default 1111);
- Representation of decimals
- Floating point numbers: divided into single precision
FLOAT[(M,D)][UNSIGNED][ZEROFILL]
and double precisionDOUBLE[(M,D)][UNSIGNED][ZEROFILL]
. M is the total number of decimal places, and D is the number of decimal places. If M and D are omitted, the value is saved according to the limitations allowed by the hardware. If UNSIGNED is specified, negative values are not allowed. - Single precision (float): A single-precision floating point number is accurate to approximately 7 decimal places (the number of digits in the integer part plus the decimal part)
- Double precision (double): A double-precision floating point number is accurate to approximately 15 decimal places (the number of digits in the integer part plus the decimal part)
- Fixed-point number: There is only one representation of decimal,
DECIMAL(M,D)
occupies M+2 bytes. Fixed-point numbers are stored in the form of strings inside MySQL, which are more precise than floating-point numbers and are suitable for representing high-precision data such as currency.
- Floating point numbers: divided into single precision
date type
Date and time types | byte | minimum value | maximum value |
---|---|---|---|
DATE | 4 | 1000-01-01 | 9999-12-31 |
DATETIME | 8 | 1000-01-01 00:00:00 | 9999-12-31 23:59:59 |
TIMESTAMP | 4 | 1970-01-01 00:00:00 | Sometime in 2038 |
TIME | 3 | -838:59:59 | 838:59:59 |
YEAR | 1 | 1901 | 2155 |
- DATETIME is a commonly used date type.
string type
type | illustrate |
---|---|
CHAR(M) | M is an integer between 0 and 255, which means that M characters can be stored (it is OK if the total number of Chinese or English characters is M) |
VARCHAR(M) | M is an integer between 0 and 65535, which means that M characters can be stored. The specific maximum size of M is closely related to the character set. Note: The maximum storage space of varchar column is 65,532 bytes. If it is an English character set (one English character occupies 1 byte), it can be placed 65532 English characters. The value you set for M during the actual development process should be considered based on your actual needs, rather than the maximum number of characters that can be stored, because exceeding the maximum number of characters that can be set will automatically report an error or warning! |
TINYTEXT | Allowed length is 0~255 characters |
TEXT | Allowed length is 0~65535 characters |
MEDIUMTEXT | Allowed length is 0~16,777,215 characters |
LONGTEXT | Allowed length is 0~4,294,967,295 characters |
- important point
- The storage space occupied by char type characters is fixed. No matter how many characters you save when using it, the space it occupies is the character space you originally set. For example, char(255), even if you only store 1 a, it still occupies 255 characters of space!
- The storage space occupied by the varchar column is variable, and the actual space occupied is determined according to the length of the characters stored! The actual space occupied by varchar(255) is the actual character length + 1 byte! The actual space occupied by varchar (more than 255) is the length of the actual character + 2 bytes! Save more space!
- During retrieval, the char column deletes the trailing spaces, because when the number of characters is not enough, spaces are added at the end. All trailing spaces will be automatically removed when taken out, while varchar retains these spaces.
- Choice: Since char is of fixed length, its processing speed is faster than varchar, but the disadvantage is a waste of storage space. So for those data whose length does not change much, you can select this column
- When saving a small amount of strings, choose char or varchar. When saving large text, you usually choose text.
BLOB type
- The blob type is used to store binary data, such as photos.
ENUM type
- enumeration type, its value range needs to be specified explicitly through enumeration when creating the table. Enumeration of
1~255
members requires 1 byte storage; for < /span>256~65535
members require 2 bytes of storage. The maximum number of members is 65535. - For example:
create table t1(flag enum('a','b','c','d'));
insert into t1 values('a'),('a'),('f');
- Data stored in the enum type is case-insensitive.
- In addition, the enum type only allows selecting a single value from the value collection, and cannot select multiple values at one time.
SET type
- set is very similar to the enum type. It is also a string object, which can contain
0~64
members. Storage varies depending on the member.1~8
A collection of members, accounting for 1 byte9~16
A collection of members, occupying 2 bytes17~24
A collection of members, occupying 3 bytes25~32
A collection of members, occupying 4 bytes33~64
A collection of members, occupying 8 bytes
- The set type can select any one or multiple elements from the allowed value set for combination. Therefore, as long as the output value is within the allowed combination range, it can be correctly injected into the set type column.
- For values outside the allowed value range, injection will not be allowed, and collections containing duplicate members will only be injected once.
- It is a better choice to use the FIND_IN_SET function to query set type data.
- For example:
select * from t16 where find_in_set('man', sex);
- For example:
SQL classification
- DDL (Data Definition Languages) statement
- Data definition statements are languages through which databases can be created, deleted, modified, etc. DDL statements are more commonly used by database administrators (DBAs) and are rarely used by developers.
- DML (Data Manipulation Languages) statements
- DML operations refer to operations on table records in the database, mainly including the insertion, update, deletion and query of table records. They are the most frequently used operations by developers daily.
- DCL (Data Control Languages) statement
- DCL statements are mainly used by DBAs to manage object permissions in the system, and are rarely used by developers.
DDL statement
- Log in to the database
msyql -u 用户名 -p
Press Enter and enter the password - Exit database
exit;
- The command terminator is
;
or\g
- The client's connection ID. This number records the number of connections to the MySQL service so far. Each new connection will automatically increase by 1.
- View database list
show databases;
- View all warnings
show warnings;
- Create database
create database;
- Select database
use 数据库;
- View data tables in the database
show tables;
- View created table information
show create table table_name;
- Delete database
drop database 数据库;
- Create table
create table 表名(
字段1名 字段1类型 列的约束条件,
字段2名 字段2类型 列的约束条件,
);
- After creating the table, you can view the table definition
desc 表名;
- The View the SQL statement that created the table
show create table 表名 \G
,\G
option enables records to be arranged vertically according to fields to better display records with longer content. , there is no need to add a semicolon after\G
. - Delete table
drop table 表名;
- Modify table
- Modify table fields
alter table 表名 modify [column] 字段名 字段定义 [first|after 字段名];
- Add table fields
alter table 表名 add [column] 字段名 字段定义 [first|after 字段名];
- Delete table field
alter table 表名 drop [column] 字段名;
- Field rename
alter table 表名 change [column] 旧的字段名 字段名 字段定义 [first|after 字段名];
Both change and modify can modify the definition of the table. The difference is that change needs to be followed by two column names, which is inconvenient, but the advantage is that change can modify the field name. - Modify the arrangement and sorting of fields. In the field adding and modifying syntax (add/change/modify) introduced earlier, there is an optional first|after field name. This option can be used to modify the position of the field in the table. New fields The default is to load at the last position in the table, and change/modify will not change the position of the field by default.
- change/first|after field name These keywords are extensions of MySQL to standard SQL and may not be applicable to other databases.
- Change table name
alter table 表名 rename [to] 新的表名;
- Modify table fields
DML statement
- Insert record
insert into 表名 (字段1,字段2,... , 字段n) values (值1, 值2, ... ,值n);
You do not need to specify the field name, but the order after the values should be consistent with the sorting of the fields. - Insert multiple records at once
insert into 表名 (字段1,字段2,... , 字段n) values (值1, 值2, ... ,值n), (值1, 值2, ... ,值n), (值1, 值2, ... ,值n),...;
- update record
- update a table
update 表名 set 字段1=值1,字段2=值2,...字段n=值n [where 条件];
- Update data in multiple tables
update 表1,表2,... 表n set 表1.字段1=表达式1,表2.字段2=表达式2,...表n.字段n=表达式n [where 条件];
Multi-table update is more used to dynamically update the fields of another table based on the fields of one table.
- update a table
- Delete Record
- Delete single table data
delete from 表名 [where 条件];
- Delete data in multiple tables
delete 表1, 表2, ... , 表n from 表1, 表2, ... 表n [where 条件];
Regardless of whether it is a single table or multiple tables, all records in the table will be deleted without adding a where condition.
- Delete single table data
- Query the records
select 字段名|* from 表名;
- Query for unique records
select distinct field1, field2 from 表名;
As long asfiled1,field2
is different in any place, it will be selected. Generally, distinct is used to filter only one field. - Conditional query
=,<,>,>=,<=,!=,
and other comparison operators can be used between multiple conditionsor,and
etc.where
followed by conditions,select * from 表名 where 条件;
- sorting and limiting,
- Exclusion order:
select * from 表名 order by 字段1 asc|desc,字段2 asc|desc,... 字段n asc|desc;
,asc
: Yuko to high,desc
: Yuko to low. - Limit: Add the limit number at the end of the statement to limit the number of queries.
limit 数字1, 数字2;
The number 1 represents which record to start fetching (starting from 0), and the number 2 represents how many records to fetch.
- Exclusion order:
- polymerization:
- sumsum
select sum(字段名) from 表名;
- count total number of records
select count(*|字段名) from 表名;
- maxmax value
select max(字段名) from 表名;
- minminimum
select min(字段名) from 表名;
- group by represents the field to be categorically aggregated (these functions above).
select [字段2],sum(字段1) from 表名 group by 字段2;
- with rollup is optional syntax, the table name is whether to re-summarize the results after classification and aggregation,
select sum(字段1) from 表名 group by 字段2 with rollup;
- The having keyword indicates conditional filtering of classified results. The difference between having and where is that having is conditional filtering of aggregated results, while where is filtering records before aggregation. Records should be filtered as much as possible. Perform filtering first.
select sum(字段1) from 表名 group by 字段2 having sum(字段1) > 1000;
- sumsum
- table join
- Table connections can be used when displaying fields from multiple tables
- Connection classification
- Inner join: Select matching records in two tables.
select 表.字段, ... from 表1,表2,...表n where [匹配的条件 表1.字段=表2.字段];
The select statement can give aliases to fields and tables and write them directly after the fields that need to be displayed in the query.select 表.字段 [字段别名], ... from 表1 [表别名],表2 [表别名],...表n [表别名] where [匹配的条件 表1.字段=表2.字段];
- Outer join: not only selects two matching records, but also selects other non-matching records.
- Outer joins include: left join and right join
- Left join: Contains all records in the left table (including no matching records in the right table)
select 字段1, 字段2 from 左表 left join 右表 on 左表.字段=右表.字段;
- Right join: contains all records in the right table (including no matching records in the left table)
select 字段1, 字段2 from 左表 right join 右表 on 左表.字段=右表.字段;
- Left joins and right joins can be converted to each other.
- Inner join: Select matching records in two tables.
- Subquery: When a query requires the results of another query to participate
- Keywords used for subqueries: in, not in, exists, not exits.
- in
select * from 表1 where 字段1 in (select 字段2 from 表2);
The sub-statement after in must return only one field. If the query result is unique (only one), you can use = instead of in. - not in is the opposite of in
- exits
select 语句 where exists(select 语句);
exits: Whether the subsequent sub-statement has queried the record, if the record is queried (regardless of whether it is null), it will return true, otherwise it will be false. - not exits is the opposite of exits
- Record union: We often encounter the need to query the data of two tables or multiple tables according to certain query conditions, and then merge the results together for display. In this case, we need to use record union.
- Multiple select statements can be realized by connecting them with union or union all.
- Difference: Union will combine multiple query results and return them after removing duplicates. Union all merges directly without deduplication.
- Union condition: The number of columns in the query must be equal.
- Query for unique records
Supplementary knowledge
- View all available character sets
show character set;
or view information_schema.character_sets. - MySQL's character set includes two concepts: character set (character) and collation rules (collation).
- Character sets are used to define how MySQL stores strings.
- Collation rules are used to define how string comparisons are performed.
- There is a one-to-many relationship between character sets and collation rules. A character set has multiple collation rules for you to choose from!
- Collation rule naming convention: they begin with the relevant character set name, usually include a language name, and end with
- _ci (ignore case)
- _cs (case sensitive)
- _bin (binary, that is, the comparison is based on the character encoding value and has nothing to do with language) ends.
- View the collation rules of the character set:
show collation like '字符集前缀%';
- MySQL internal character set and collation rule settings
- Server character set and collation rule settings omitted
- Database character set and collation rule settings
View the character set and collation rules of the current database:CREATE DATABASE db_name [[DEFAULT] CHARACTER SET charset_name] [[DEFAULT] COLLATE collation_name]
Change character set and collation rules:show variables like 'character_set_database'; show variables like 'collation_database';
ALTER DATABASE db_name [[DEFAULT] CHARACTER SET charset_name] [[DEFAULT] COLLATE collation_name]
- Table character set and collation rule settings
4. Field (column) character set and collation rulesCREATE TABLE tbl_name (column_list) [DEFAULT CHARACTER SET charset_name [COLLATE collation_name]] ALTER TABLE tbl_name [DEFAULT CHARACTER SET charset_name] [COLLATE collation_name]
The probability of encountering this situation is relatively small. This is just a flexible setting method provided by MySQL for us
- MySQL connection character set setting
During the process, you must set it correctly and be honest and trustworthy. If all settings are normal, the server will automatically convert according to the character set you set. However, It is also necessary to avoid the conversion process, it is best to set them to the same encoding!
Connection character set settings: character set for interaction between client and server-
For interaction between client and server segments, MySQL provides 3 different parameters:
- character_set_client: Character set used by client source data
- character_set_connection: connection layer character set
- character_set_results: Return the result character set
Knowledge expansion: The general process of character set conversion during the interaction of data between the client and the server - When MySQL Server receives the request, it converts the request data from character_set_client to character_set_connection;
- Before performing internal operations, convert the request data from character_set_connection to the internal operation character set. The internal operation character set is determined as follows:
- Use the character set set for each data field;
- If the above value does not exist, the character set set in the corresponding data table will be used;
- If the above value does not exist, the character set set by the corresponding database will be used;
- If the above value does not exist, the character set set by the server is used.
- Converts operation results from the internal operation character set to character_set_results.
-
The character sets set by these three parameters should be the same, and the character set used by the client is indeed the value of the parameter character_set_client, so that the user's data can be returned and output correctly.
-
View current settings: show variables like 'character_set%';
Modify:
set names character set, you can modify the values of 3 parameters at the same time , valid for this time
can also be set in the configuration file:
[mysql]
default-character-set=character Set -
The characters used by the client, the character set used by the connection layer, the character set used internally, and the character set used by the return layer should all be set to the same layer, and the character set used by the client is indeed the value of the character_set_client parameter, so it will definitely not There will be problems!
-
- MySQL provides some operation symbols for us to use in SQL statements. For example, when we need to perform operations on a certain value or a certain field in the SQL statement, we can use these operators.
1.算数运算符
运算符 作用
+ 加法
- 减法
* 乘法
/,DIV 除法,返回商
%,MOD 取余数
2.比较运算符
运算符 作用
= 等于
<>或!= 不等于
<=> 可以用于null值的比较
< 小于
<= 小于等于
> 大于
>= 大于等于
BETWEEN 存在指定范围
IN 存在于指定集合
IS NULL 为NULL
IS NOT NULL 不为NULL
LIKE 通配符匹配
REGEXP或RLIKE 正则表达式匹配
3.逻辑运算符
逻辑运算符又称为布尔运算符,用来确认表达式的真和假
运算符 作用
NOT或! 逻辑非
AND或&& 逻辑与
OR或|| 逻辑或
XOR 逻辑异或
4.运算符的优先级
在实际运行的时候,实际上很少有人能够将运算符的优先级熟练记忆
很多情况下我们都是用“()”来将需要优先的操作括起来,这样既起到了优先的作用,又使得其他用户看起来更易于理
解
- Commonly used functions
1.字符串函数
函数 功能
CONCAT(S1,S2,...Sn) 连接S1,S2,...Sn为一个字符串
INSERT(str,x,y,instr) 将字符串str从第x位置开始,y个字符长的字符串换位字符串instr
LOWER(str) 将字符串str中所有字符变为小写
UPPER(str) 将字符串str中所有字符变为大写
LEFT(str,x) 返回字符串str最右边的x个字符
RIGHT(str,x) 返回字符串str最右边的x个字符
LPAD(str,n,pad) 用字符串pad对str最左边进行填充,直到长度为n个字符长度
RPAD(str,n,pad) 用字符串pad对str最右边进行填充,直到长度为n个字符长度
LTRIM(str) 去掉字符串str左侧的空格
RTRIM(str) 去掉字符串str行尾的空格
REPEAT(str,x) 返回str重复x次的结果
REPLACE(str,a,b) 用字符串b替换字符串str中所有出现的字符串a
STRCMP(s1,s2) 比较字符串s1和s2
TRIM(str) 去掉字符串行尾和行头的空格
SUBSTRING(str,x,y) 返回从字符串str x位置起y个字符长度的字符串
LENGTH(str) 返回字符串长度
2.数值函数
函数 功能
ABS(x) 返回x的绝对值
CEIL(x) 返回大于x的最小整数值
FLOOR(x) 返回小于x的最大整数值
MOD(x,y) 返回x/y的模
RAND() 返回0-1内的随机值
ROUND(x,y) 返回参数x的四舍五入的有y位小数的值
TRUNCATE(x,y) 返回数字x截断为y位小数的结果
3.日期和时间函数
函数 功能
CURDATE() 返回当前日期
CURTIME() 返回当前时间
NOW() 返回当前的日期和时间
UNIX_TIMESTAMP(date) 返回日期date的UNIX时间戳
FROM_UNIXTIME() 返回UNIX时间戳的日期值
WEEK(date) 返回日期date为一年中的第几周
YEAR(date) 返回日期date的年份
HOUR(time) 返回time的小时值
MINUTE(time) 返回time的分钟值
MONTHNAME(date) 返回date的月份名
DATE_FORMAT(date,fmt) 返回按字符串fmt格式化日期date值
DATE_ADD(add,INTERVAL expr type) 返回一个日期或时间值加上一个时间间隔的时间值
DATEDIFF(expr,expr2) 返回起始时间expr和结束时间expr2之间的天数
4.流程函数
函数 功能
IF(value,t,f) 如果value是真,返回t,否则返回f
IFNULL(value1,value2) 如果value1不为null,返回value1,否则返回value2
CASE WHEN [value1] THEN [result1]...ELSE[default]END 如果value1是真,返回result1,否则返回default
CASE [expr] WHEN [value1] THEN[result1]...ELSE[default]END 如果expr等于value1,返回result1,否则返回
default
5.其他常用函数
函数 功能
DATABASE() 返回当前数据库名
VERSION() 返回当前数据库版本
USER() 返回当前登录用户名
INET_ATON(IP) 返回IP地址的数字表示
INET_NTOA(num) 返回数字代表的IP地址
PASSWORD(str) 返回字符串str的加密版本
MD5() 返回字符串str的MD5值