当前位置:网站首页>Basic SQL tutorial
Basic SQL tutorial
2022-07-03 15:06:00 【Initial-T】
Reproduced from teacher liaoxuefeng's tutorial :
SQL course - Liao Xuefeng's official website
One summary
In short ,SQL It's the standard computer language for accessing and processing relational databases .
Data base is a kind of software that specially manages data . Applications do not need to manage data themselves , Instead, it reads and writes data through the interface provided by the database software .
Common types
name | type | explain |
INT | integer | 4 Byte integer type , The scope is about +/-21 Billion |
BIGINT | Long integer | 8 Byte integer type , The scope is about +/-922 Billion |
REAL | floating-point | 4 Byte float , The scope is about +/-10 38 |
DOUBLE | floating-point | 8 Byte float , The scope is about +/-10 308 |
DECIMAL(M,N) | High precision decimal | Decimal with precision specified by the user , for example ,DECIMAL(20,10) All in all 20 position , Where decimal 10 position , Usually used in financial calculations |
CHAR(N) | Fixed length string | Store a string of specified length , for example ,CHAR(100) Always store 100 Character string |
VARCHAR(N) | Variable length string | Store variable length strings , for example ,VARCHAR(100) Can be stored 0~100 Character string |
BOOLEAN | Boolean type | Storage True perhaps False |
DATE | The date type | Storage date , for example ,2018-06-22 |
TIME | Time type | Storage time , for example ,12:20:59 |
DATETIME | Date and time type | Storage date + Time , for example ,2018-06-22 12:20:59 |
Generally speaking ,BIGINT It can meet the needs of integer storage ,VARCHAR(N) It can meet the requirements of string storage , These two types are the most widely used .
Tutorial conventions :SQL Keywords are always capitalized , To highlight , Table and column names are in lowercase .
Two install
mysql Two engines
- InnoDB: from Innobase Oy The company developed a database engine that supports transactions ,2006 By the Oracle Acquisition ;
- MyISAM:MySQL Early integrated default database engine , Unsupported transaction .
Branch :
- MariaDB: from MySQL An open source branch version created by the founder of
- Aurora: from Amazon Improved one MySQL edition
- PolarDB: from Alibaba Improved one MySQL edition
Sign in : mysql -u root -p, Then enter the password
3、 ... and relational model
- Each row of a table is called a record (Record), Records are data in a logical sense .
- Each column of a table is called a field (Column), Each row of records in the same table has the same number of fields . Field defines the data type ( integer 、 floating-point 、 character string 、 Date, etc. ), And whether it is allowed to be NULL. Be careful null No 0, It's not an empty string "".
In a relational database , Relationships are maintained through primary and foreign keys . For relational tables , There is a very important constraint , That is, any two records cannot be repeated . It can uniquely distinguish different records through a certain field , This field is called Primary key .
Requirements for primary keys , The key point is : Once the record is inserted into the table , You'd better not modify the primary key . A basic principle for selecting primary keys is : Do not use any business-related fields as primary keys .
Generally, this field is named id. Common can be used as id The types of fields are :
- Self increasing integer type : The database will automatically assign an auto increment integer to each record when inserting data , So we don't have to worry about duplicate primary keys at all , You don't need to generate the primary key in advance ;
- Globally unique GUID type : Use a globally unique string as the primary key , similar 8f55d96b-8acc-4636-8cb8-76bf8abc2f57.
You can use multiple columns as a federated primary key , But federated primary keys are not commonly used .
stay students In the table , adopt class_id Field of , You can associate data with another table , Such columns are called foreign keys .
Because foreign key constraints will reduce the performance of the database , Most Internet applications pursue speed , Do not set foreign key constraints , It is Only the application itself can ensure the correctness of logic .
Through the middle table , We define a “ Many to many ” Relationship . Other applications will split a large table into two one-to-one tables , The purpose is to separate the frequently read and infrequently read fields , For better performance .
The efficiency of the index depends on whether the value of the index column is hash . Using primary key index is the most efficient , Because the primary key is guaranteed to be absolutely unique . By creating a unique index , It can ensure that the value of a column is unique .
Four Query data
Use SELECT * FROM students when ,SELECT Is the key word , Indicates that a query will be executed ,* Express “ All columns ”,FROM Indicates which table to query .SELECT The result of the query is a two-dimensional table .
SELECT The statement does not require FROM Clause . Many inspection tools will execute one SELECT 1; To test the database connection .
adopt WHERE Conditions of the query , You can filter out records that meet the specified conditions , Instead of all the records of the whole table .
Use <> Judgment is not equal | score <> 80 | name <> 'abc' | |
Use LIKE Judge similarity | name LIKE 'ab%' | name LIKE '%bc%' | % For any character , for example 'ab%' Will match 'ab','abc','abcd' |
Use SELECT * Represents all columns of the query table , Use SELECT Column 1, Column 2, Column 3 You can only return the specified column , This operation is called projection . You can rename the columns of the result set SELECT Column 1 Alias 1, Column 2 Alias 2 FROM XXX
Use ORDER BY You can sort the result set ; You can sort multiple columns in ascending order 、 Reverse sort .ASC DESC
Use LIMIT OFFSET The result set can be paged , Each query returns a portion of the result set ;
OFFSET It's optional , If only write LIMIT 15, So it's equivalent to LIMIT 15 OFFSET 0.OFFSET If the maximum number of queries is exceeded, no error will be reported , Instead, we get an empty result set .
SQL Special aggregation functions are provided , Use aggregate functions for queries , Aggregate query . except COUNT() Out of function ,SQL The following aggregation functions are also provided :
function | explain |
COUNT | Calculate the quantity of a column |
SUM | Calculate the total value of a column , The column must be of numeric type |
AVG | Calculate the average of a column , The column must be of numeric type |
MAX | Calculate the maximum value of a column |
MIN | Calculate the minimum value of a column |
Pay special attention to : If the aggregate query WHERE The condition does not match any lines ,COUNT() Returns the 0, and SUM()、AVG()、MAX() and MIN() Returns the NULL
GROUP BY Can be grouped
Multi table query is also called Cartesian query , Be very careful when using Cartesian queries , The result set is the product of the number of rows in the target table . Using multi table query, you can get M x N rows ;
SQL It also allows you to set an alias for the table , Let's make the reference a little more concise in projection queries .
The most commonly used internal connection ——INNER JOIN.
- First make sure the main table , Still use FROM The grammar of ;
- Then determine the tables that need to be connected , Use INNER JOIN The grammar of ;
- Then determine the connection conditions , Use ON , The condition here is s.class_id = c.id, Express students Tabular class_id Column and classes Tabular id Columns of the same row need to be joined ;
- Optional : add WHERE Clause 、ORDER BY Equal clause
Suppose the query statement is :
SELECT ... FROM tableA JOIN tableB ON tableA.column1 = tableB.column2;
We put tableA Look at the left table , hold tableB Look at the right table .
INNER JOIN It's a selection of records that exist in both tables :
LEFT OUTER JOIN Is to select the records that exist in the left table :
RIGHT OUTER JOIN Is to select the records that exist in the right table :
FULL OUTER JOIN Then select the records that exist in the left and right tables :
5、 ... and Additions and deletions
increase : INSERT
Such as :
INSERT INTO students (class_id, name, gender, score) VALUES (2, ' Daniel ', 'M', 80);
You can also insert multiple , Such as
INSERT INTO students (class_id, name, gender, score) VALUES (1, ' Dabao ', 'M', 87), (2, ' Er Bao ', 'M', 81);
Change : UPDATE
UPDATE students SET name=' Daniel ', score=66 WHERE id=1;
stay UPDATE In the sentence , You can use expressions when updating fields .
UPDATE students SET score=score+10 WHERE score<80;
Last , Be especially careful ,UPDATE Statement can have no WHERE Conditions , for example :
UPDATE students SET score=60;
At this time , All records of the entire table will be updated .
Delete : DELETE
DELETE FROM students WHERE id=1;
Be especially careful , and UPDATE similar , No WHERE Conditions of the DELETE Statement will delete the data of the entire table :
DELETE FROM students;
At this time , All records of the entire table will be deleted . therefore , In execution DELETE You should also be very careful when speaking , It's better to use SELECT Statement to test WHERE Whether the condition filters out the desired recordset , And then use DELETE Delete .
6、 ... and MYSQL
client
MySQL Client and MySQL Server The relationship is as follows :
stay MySQL Client The SQL Statement passing TCP The connection is sent to MySQL Server.
Login statement :
mysql -h 10.0.1.99 -u root -p
Command line program
mysql It's actually MySQL client , real MySQL The server program is mysqld, Running in the background
management MYSQL
library
To list all databases , Use command SHOW:
mysql> SHOW DATABASES;
To create a new database , Use command CREATE:
mysql> CREATE DATABASE test;
To delete a database , Use command DROP:
mysql> DROP DATABASE test;
When operating on a database , First switch it to the current database USE:
mysql> USE test;
surface
List all tables in the current database , Use command SHOW:
mysql> SHOW TABLES;
To see the structure of a table , Use command DESC:
mysql> DESC students;
You can also use the following command to view the SQL sentence SHOW CREATE TABLE:
mysql> SHOW CREATE TABLE students;
Create tables using CREATE TABLE sentence , And delete tables using DROP TABLE sentence :
mysql> DROP TABLE students;
It's more complicated to modify the table , Use ALTER TABLE. If you want to give students Add a new column to the table birth:
ALTER TABLE students ADD COLUMN birth VARCHAR(10) NOT NULL;
To be modified birth Column , For example, change the column name to birthday, Change the type to VARCHAR(20):
ALTER TABLE students CHANGE COLUMN birth birthday VARCHAR(20) NOT NULL;
To delete a column , Use :
ALTER TABLE students DROP COLUMN birthday;
sign out MySQL
Use EXIT Command exit MySQL:
mysql> EXIT
Practical sentences
Use REPLACE sentence , So you don't have to query first , Then decide whether to delete and then insert :
REPLACE INTO students (id, class_id, name, gender, score) VALUES (1, 1, ' Xiao Ming ', 'F', 99);
I want to insert a new record (INSERT), But if the record already exists , Just update the record , here , have access to INSERT INTO ... ON DUPLICATE KEY UPDATE ... sentence :
INSERT INTO students (id, class_id, name, gender, score) VALUES (1, 1, ' Xiao Ming ', 'F', 99) ON DUPLICATE KEY UPDATE name=' Xiao Ming ', gender='F', score=99;
I want to insert a new record (INSERT), But if the record already exists , Don't do anything, just ignore , here , have access to INSERT IGNORE INTO ... sentence :
INSERT IGNORE INTO students (id, class_id, name, gender, score) VALUES (1, 1, ' Xiao Ming ', 'F', 99);
If you want to snapshot a table , That is to copy the data of the current table to a new table , Can combine CREATE TABLE and SELECT:
-- Yes class_id=1 Take a snapshot of your records , And stored as a new table students_of_class1:
CREATE TABLE students_of_class1 SELECT * FROM students WHERE class_id=1;
Write the average grade of each class in one sentence :
INSERT INTO statistics (class_id, average) SELECT class_id, AVG(score) FROM students GROUP BY class_id;
Use FORCE INDEX Force the query to use the specified index . for example :
> SELECT * FROM students FORCE INDEX (idx_class_id) WHERE class_id = 1 ORDER BY id DESC;
The premise is index idx_class_id There must be .
7、 ... and Business
1 Concept
This function of operating multiple statements as a whole , It's called a database transaction .
Database transactions have ACID this 4 A feature :
- A:Atomic, Atomicity , Will all SQL To perform as an atomic unit of work , Or all , Or none at all ;
- C:Consistent, Uniformity , After the transaction completes , The state of all data is consistent , namely A Just subtract... From the account 100,B The account must have added 100;
- I:Isolation, Isolation, , If there are multiple transactions executing concurrently , Changes made by each transaction must be isolated from other transactions ;
- D:Duration, persistence , After the transaction is completed , Changes to database data are persisted .
Single SQL sentence , The database system automatically executes it as a transaction , This kind of transaction is called implicit transaction .
You have to manually turn multiple SQL Statement is executed as a transaction , Use BEGIN Start a transaction , Use COMMIT Commit a transaction , This kind of transaction is called explicit transaction
BEGIN; UPDATE accounts SET balance = balance - 100 WHERE id = 1; UPDATE accounts SET balance = balance + 100 WHERE id = 2; COMMIT;
Use ROLLBACK Roll back
BEGIN; UPDATE accounts SET balance = balance - 100 WHERE id = 1; UPDATE accounts SET balance = balance + 100 WHERE id = 2; ROLLBACK;
SQL The standard defines 4 Kind of isolation level , Corresponding to the possible data inconsistency :
Isolation Level | Dirty reading (Dirty Read) | It can't be read repeatedly (Non Repeatable Read) | Fantasy reading (Phantom Read) |
Read Uncommitted | Yes | Yes | Yes |
Read Committed | - | Yes | Yes |
Repeatable Read | - | - | Yes |
Serializable | - | - | - |
2 Four kinds of isolation
- stay Read Uncommitted Under isolation level , One transaction may read data updated but not committed by another transaction , This data may be dirty .
- stay Read Committed Under isolation level , A transaction may encounter a non repeatable read (Non Repeatable Read) The problem of . Nonrepeatable reading means , In a business , Read the same data multiple times , Before the end of the business , If another transaction happens to modify this data , that , In the first transaction , The data read twice may be inconsistent .
- stay Repeatable Read Under isolation level , A transaction may encounter unreal reading (Phantom Read) The problem of . Unreal reading means , In a transaction , The first time to query a record , Found no , however , When trying to update this nonexistent record , To succeed , also , Read the same record again , It magically appears .
- Serializable It's the strictest level of isolation . stay Serializable Under isolation level , All transactions are executed in order , therefore , Dirty reading 、 It can't be read repeatedly 、 Unreal reading doesn't show up . although Serializable Transactions at the isolation level have the highest security , however , Because the transaction is serial execution , So the efficiency will be greatly reduced , The performance of the application will degrade dramatically . If there is no particularly important situation , I don't usually use Serializable Isolation level .
Default isolation level
If the isolation level is not specified , The database will use the default isolation level . stay MySQL in , If you use InnoDB, The default isolation level is Repeatable Read.
边栏推荐
- 使用Tengine解决负载均衡的Session问题
- Unity hierarchical bounding box AABB tree
- Yolov5 advanced nine target tracking example 1
- 什么是embedding(把物体编码为一个低维稠密向量),pytorch中nn.Embedding原理及使用
- 零拷贝底层剖析
- Global and Chinese markets for ionization equipment 2022-2028: Research Report on technology, participants, trends, market size and share
- Yolov5 advanced 8 format conversion between high and low versions
- Open under vs2019 UI file QT designer flash back problem
- C string format (decimal point retention / decimal conversion, etc.)
- Leetcode sword offer find the number I (nine) in the sorted array
猜你喜欢
How to color ordinary landscape photos, PS tutorial
Finally, someone explained the financial risk management clearly
C language DUP function
什么是embedding(把物体编码为一个低维稠密向量),pytorch中nn.Embedding原理及使用
Unity hierarchical bounding box AABB tree
cpu飙升排查方法
What are the composite types of Blackhorse Clickhouse, an OLAP database recognized in the industry
解决pushgateway数据多次推送会覆盖的问题
零拷贝底层剖析
[ue4] material and shader permutation
随机推荐
What is embedding (encoding an object into a low dimensional dense vector), NN in pytorch Principle and application of embedding
4-29——4.32
Mmdetection learning rate and batch_ Size relationship
【Transformer】入门篇-哈佛Harvard NLP的原作者在2018年初以逐行实现的形式呈现了论文The Annotated Transformer
【pytorch学习笔记】Datasets and Dataloaders
App全局异常捕获
mmdetection 学习率与batch_size关系
【注意力机制】【首篇ViT】DETR,End-to-End Object Detection with Transformers网络的主要组成是CNN和Transformer
Apache ant extension tutorial
基于SVN分支开发模式流程浅析
Remote server background hangs nohup
Déformation de la chaîne bm83 de niuke (conversion de cas, inversion de chaîne, remplacement de chaîne)
[graphics] real shading in Unreal Engine 4
406. Reconstruct the queue according to height
Global and Chinese markets of AC electromechanical relays 2022-2028: Research Report on technology, participants, trends, market size and share
Solve the problem that PR cannot be installed on win10 system. Pr2021 version -premiere Pro 2021 official Chinese version installation tutorial
[opengl] face pinching system
Global and Chinese markets for sterile packaging 2022-2028: Research Report on technology, participants, trends, market size and share
Global and Chinese market of optical fiber connectors 2022-2028: Research Report on technology, participants, trends, market size and share
[opengl] pre bake using computational shaders