当前位置:网站首页>Graphical SQL is too vivid
Graphical SQL is too vivid
2022-07-27 14:47:00 【Ah size】
This paper introduces the design idea of relational database : stay SQL in , It's all about .
There are many great design ideas and ideas in the computer field , for example :
- stay Unix in , Everything is a document .
- In an object-oriented programming language , Everything is the object .
Relational databases also have their own design ideas : stay SQL in , It's all about .
relational model
relational model (Relational model) from E.F.Codd Doctor Yu 1970 in , Based on the concept of relation in set theory ; Both the entity objects in the real world and the relations between them are represented by relations . The relationship we see in the database system is a two-dimensional table (Table), By line (Row) And column (Column) form . therefore , It can also be said that a relational table is a collection of data rows .

The relational model consists of data structures 、 Relationship operation 、 Integrity constraints consist of three parts .
The data structure in a relational model is a relational table , Including the basic table 、 Derived tables ( Query results ) And virtual tables ( View ).
Common relational operations include adding 、 Delete 、 Modification and query (CRUD), What you use is SQL Language . The query operation is the most complex , Include options (Selection)、 Projection (Projection)、 Combine (Union)、 intersection (Intersection)、 Difference set (Exception) And Cartesian product (Cartesian product) etc. .
Integrity constraints are used to maintain data integrity or meet business constraints , Including physical integrity ( Primary key constraint )、 Referential integrity ( Foreign key constraints ) And user-defined integrity ( Non empty constraint 、 Unique constraint 、 Check constraints and defaults ).
Our topic today is relational operating languages , That is to say SQL.
Face the set
SQL( Structured query language ) Is the standard language for operating relational databases .SQL Very close to English , It's very simple to use . It is designed to take into account the needs of non-technical personnel at the beginning of its design , We usually just need to state the desired result (What), And the process of data processing (How) Give it to the DBMS . So ,SQL Is the real programming language for people !
Next, we will analyze the various operation statements of relations ; The purpose is to let people understand SQL Is a set oriented programming language , Its object of operation is a collection , The result of the operation is also a set .
In a relational database , Relationship 、 surface 、 Set three usually represent the same concept .
SELECT
Here is a simple query statement :
SELECT employee_id, first_name, last_name, hire_date FROM employees;
Its function is to employees Query employee information in the table . obviously , We all know FROM And then there's a table ( Relationship 、 aggregate ). More Than This , The result of the whole query statement is also a table . therefore , We can use the above query as a table :
SELECT * FROM ( SELECT employee_id, first_name, last_name, hire_date
FROM employees) t;
Queries in parentheses are called derived tables , We gave it an alias called t. Again , The entire query result is also a table ; This means that we can continue to nest , It's boring though .
Let's see one more PostgreSQL Example in :
-- PostgreSQLSELECT *
FROM upper( 'sql');
| upper |
| -------|
| SQL |
upper() It's a capital conversion function . It appears again FROM clause , It means that its result is also a table , nothing but 1 That's ok 1 Special table of columns .
SELECT Clause is used to specify the fields to be queried , Can contain expressions 、 Function values, etc .SELECT In relational operations, it's called projection (Projection), Look at the diagram below, it should be easier to understand .

except SELECT outside , There are also some commonly used SQL Clause .
WHERE Used to specify the conditions for data filtering , In relational operations it's called selection (Selection), The schematic diagram is as follows :

ORDER BY Used to sort the results of a query , The schematic diagram is as follows :

All in all ,SQL Can complete all kinds of data operation , Such as filtering 、 grouping 、 Sort 、 Limit quantity, etc ; The objects of all these operations are relational tables , The result is also a relational table .

In these relational operations , There is a special one , Grouping is .
GROUP BY
grouping ( GROUP BY) Operations are different from other relational operations , Because it changes the structure of relationships . Take a look at the following example :
SELECT department_id, count(*), first_name FROM employees
GROUP BY department_id;
The purpose of this statement is to count the number of employees by Department , There's a syntax error, but there's a syntax error , Namely first_name Cannot appear in the list . The reason is that if you group by Department , Each department contains multiple employees ; Unable to determine which employee's name needs to be displayed , This is a logical mistake .
So ,GROUP BY Changed set elements ( data row ) Structure , Created a whole new relationship . The schematic diagram of grouping operation is as follows :

For all that ,GROUP BY The result is still a collection .
UNION
SQL The most obvious manifestation of the set oriented feature is UNION( Union operation )、INTERSECT( Intersection operation ) and EXCEPT/MINUS( Subtraction operation ).
The function of these set operators is to combine two sets into a set , So the following conditions need to be met :
The number and order of fields in both sets must be the same ;
The types of the corresponding fields in the sets on both sides must match or be compatible with .
say concretely ,UNION and UNION ALL Used to compute the union of two sets , Returns the data that appears in the first query result or the second query result . The difference is UNION Eliminating duplicate data in the results ,UNION ALL Duplicate data is preserved . Here is UNION Schematic diagram of operation :

INTERSECT The operator is used to return the common part of two sets , That is, the data that appears in both the first query result and the second query result , And it excludes duplicate data from the results .INTERSECT The schematic diagram of the operation is as follows :

EXCEPT perhaps MINUS The operator is used to return the difference between two sets , It appears in the first query result , But not in the second query result , And it excludes duplicate data from the results .EXCEPT The schematic diagram of the operator is as follows :

besides ,DISTINCT Operators are used to de duplicate data , That is, to exclude duplicate elements from the set .
SQL The concept of relation in mathematics comes from the set theory in mathematics , therefore UNION、INTERSECT and EXCEPT They come from Union in set theory (∪\cup∪)、 intersection (∩\cap∩) And subtraction (∖\setminus∖) operation . It should be noted that , Sets in set theory do not allow duplicate data , however SQL allow . therefore ,SQL Sets in are also called multisets (multiset); Multiple sets and sets in set theory are disordered , however SQL Can pass ORDER BY Clause to sort the query results .
JOIN
stay SQL in , Not only are entity objects stored in relational tables , Relationships between objects are also stored in relational tables . therefore , When we want to get the relevant data , Need to use another operation : Link query (JOIN).
common SQL Join query type includes inner join 、 External connection 、 Cross connect, etc . among , External connection can be divided into left outer connection 、 Right outer connection and all outer connection .
Internal connection (Inner Join) Returns the data in two tables that satisfy the join condition , The principle of internal connection is shown in the figure below :

The left outer join (Left Outer Join) Return all the data in the left table ; For the right table , Return the data that satisfies the connection condition ; If not, return null value . The principle of the left outer connection is shown in the figure below :

Right connection (Right Outer Join) Return all the data in the right table ; For the left watch , Return the data that satisfies the connection condition , If not, return null value . The right outer connection and the left outer connection are interchangeable , The following two are equivalent :
t1 RIGHT JOIN t2t2 LEFT JOIN t1
Full outer join (Full Outer Join) It is equivalent to left outer join plus right outer join , All the data in the left and right tables are returned at the same time ; For data in two tables that do not meet the join condition, null value is returned . The principle of all external connection is shown in the figure below :

Cross join is also called Cartesian product (Cartesian Product). A cross join of two tables is equivalent to a pairwise combination of all rows in one table and all rows in another table , The number of results is multiplied by the number of rows in two tables . The principle of cross connection is shown in the figure below :

There are other types of connections as well as semi connections (SEMI JOIN)、 Anti connect (ANTI JOIN).
Set operations combine two sets into a larger or smaller set ; Join queries convert two sets into a larger or smaller collection , At the same time, you get a bigger element ( More columns ). Most of the time, set operations can be implemented through join queries , for example :
SELECT department_id FROM departments
UNION
SELECT department_id
FROM employees;
Equivalent to :
SELECT COALESCE(d.department_id, e.department_id) FROM departments d
FULL JOIN employees e ON (e.department_id = d.department_id);
We've introduced many examples of queries , Let's take a look at other data operations .
DML
DML Represents a data manipulation language , That is to insert 、 Update and delete . Here's an example of inserting :
CREATE TABLE test( id int);-- MySQL、SQL Server etc.
INSERT INTO test( id) VALUES ( 1),( 2),( 3);
-- Oracle
INSERT INTO test( id)
( SELECT 1 AS id FROM DUAL
UNION ALL
SELECT 2 FROM DUAL
UNION ALL
SELECT 3 FROM DUAL);
We passed a INSERT The statement inserts 3 Bar record , Or insert an inclusion 3 Relation table of records . because ,UNION ALL It returns a relational table .VALUES It also specifies a relational table , stay SQL Server and PostgreSQL The following statements are supported in :
SELECT *FROM (
VALUES( 1),( 2),( 3)
) test( id);
We've already said ,FROM And then there's a relationship table , So here VALUES Is the same . Because we often insert a single record , I don't realize that it's actually a table based operation .
Again ,UPDATE and DELETE Statements are also operations in relation tables ; It's just that we're used to talking about updating a row of data or deleting several records .
边栏推荐
- MySQL advanced II. Logical architecture analysis
- How to solve cache avalanche, breakdown and penetration problems
- Photo album based on gec6818 development board
- PROFINET 模拟器使用教程
- Navicate reports an error access violation at address 00000000
- Is there a regular and safe account opening platform for gold speculation
- Detoxify! After Harbin Institute of technology was disabled MATLAB, domestic industrial software fought back domineering
- JS epidemic at home, learning can't stop, 7000 word long text to help you thoroughly understand the prototype and prototype chain
- 【STM32】EXTI
- 视觉系统设计实例(halcon-winform)-9.文字显示
猜你喜欢

Construction and empirical research of post talent demand analysis framework based on recruitment advertisement

Shell programming specifications and variables

万字详解 Google Play 上架应用标准包格式 AAB

What you want most is the most comprehensive summary of C language knowledge. Don't hurry to learn

DVWA full level customs clearance tutorial

机场云商sign解析

2022年中国网络视频市场年度综合分析

腾讯二面:@Bean 与 @Component 用在同一个类上,会怎么样?

c语言分层理解(c语言数组)

股票买卖4
随机推荐
2022 Niuke multi School II_ E I
Toward Fast, Flexible, and Robust Low-Light Image Enhancement(实现快速、灵活和稳健的弱光图像增强)CVPR2022
Hdu4496 d-city [concurrent search]
一篇文章看懂JS执行上下文
Simple encapsulation steps of request data request of uniapp
Detoxify! After Harbin Institute of technology was disabled MATLAB, domestic industrial software fought back domineering
Basic exercises of C language
idea打jar包与引入jar包
TXT把换行 替换为空格或者取消换行
文献翻译__基于自适应全变差L1正则化的椒盐图像去噪
SLAM综述阅读笔记四:A Survey on Deep Learning for Localization and Mapping: Towards the Age of Spatial 2020
软件产品第三方测试费用为什么没有统一的报价?
Hard deduction SQL statement exercises, wrong question records
通过VN1630/VN7640的I/O功能来确认电源设置电压的时间精确度
2022牛客多校二_ E I
Database storage series (1) column storage
Dynamic programming - stock trading 5
Who can't capture packets these days? Wireshark packet capture and common protocol analysis are for you!
如何帮助企业优化Office管理
Toward fast, flexible, and robust low light image enhancement cvpr2022