Data Application Master's SQL Basic Tutorial Sharing 8-Subqueries, Joins, and Combined Queries

6. Subqueries

More complex subqueries

1. Sub query

【Introduction to knowledge points】

So far, we have used WHERE to perform many simple queries, and queries with one condition and multiple conditions have been processed.

So what is a subquery? Think of subqueries as nested structures, that is, queries contained within a query.

Subqueries usually use keywords such as IN and ALL, except for IN, which we will introduce in the next chapters.

For example, if we want to query the student ID, name and credits in the student table, if the credits are greater than 25, we can use subquery:

SELECT ID,SName,Credit FROM Student
WHERE Credit IN
  (SELECT Credit FROM Student
   WHERE Credit > 25);

 

 

Of course, this example is just to illustrate the sub query, the actual operation is meaningless, and the sub query will be more practical in multi-table query.
This also reflects the efficiency of sub-query execution. In practice, we recommend that you use sub-queries appropriately.
In addition, there is no indentation requirement in SQL. In the example, indentation is used to divide statement blocks, making statements easier to read and logic clearer. Good habits need to be developed slowly.

2、ALL\SOME\ANY

【Introduction to knowledge points】

ALL can compare the value of the column with all the values ​​in a set, and return TRUE if all the results of the comparison match.

ANY or SOME, similar in meaning to IN, returns TRUE as long as a value is matched.
But ANY is different from IN. ANY can only be used for sub-queries, while IN can directly match the list without matching through sub-queries.

For example, if we want to find students with 28 or 30 credits, ANY can only write:

WHERE Credit = ANY
  (SELECT Credit FROM Student
  WHERE (Credit = 30) OR (Credit = 28));

 

 

And with IN, you can write it directly like this:

WHERE Credit IN (28,30);

 

 

【Example】

Take the query student table as an example that meets the conditions of students whose credits are greater than 25, and use ALL to achieve our query purpose.
Compare and match all items with less than 25 credits in the credit column, and return TRUE only if the conditions are met.

SELECT * FROM Student
WHERE Credit > ALL -- Creidt should match all values ​​in ALL
  (SELECT Credit FROM Student
   WHERE Credit <= 25);

 

 

3. Summary

【Introduction to knowledge points】

1. Sub-queries can be used in FROM statements or in WHERE statements, which are actually SELECT sub-statements nested in some SQL statements;
2. As we have mentioned before, when sub-queries are used It needs to be included with parentheses, and combined with indentation and line breaks to maintain the readability of its statement;
3. Subqueries are executed from the inside out;
4. In general, sorting is not allowed in subqueries, that is ORDER BY cannot be used.

7. Connect

table to table join

1, the connection of the table

【Introduction to knowledge points】

Before learning the connection, the robot created a new table Listudent, which is the student information of Literature major, including student ID, college LID, name SName, gender Sex, class Class, credits Credit, birthplace Birthplace, etc. student information.



 

[Example]
Join (JOIN) in SQL is a powerful function, it can combine two or more tables, and can connect them through primary key and foreign key.
PS: When querying multiple tables, we recommend specifying specific columns in the form of table names and column names.

View the SQL statement, click Run, and see how the Student table and the Listudent table perform the join query

SELECT Student.ID,Student.SName,Listudent.Class FROM Student,Listudent
WHERE Student.ID = Listudent.ID;

 

 

2、INNER JOIN

【Introduction to knowledge points】

The INNER JOIN keyword can also join two tables and get the row data, requiring at least one match.
Its syntax is as follows:

SELECT COLUMN, COLUMN, FROM TABLE 1
INNER JOIN 表2
ON table1.columns = table2.columns;

 

 

【Example】

Use INNER JOIN to join 2 tables and query the information of students whose credits are higher than 20.

SELECT Student.ID,Student.SName,Student.Credit,Listudent.Class FROM student
INNER JOIN Listudent -- INNER JOIN two tables  
ON Student.ID = Listudent.ID
WHERE Listudent.Credit > 20; -- credit judgment condition

 

 

3、RIGHT\LEFT JOIN

【Introduction to knowledge points】

RIGHT JOIN joins tables and returns all rows of data from the right table, regardless of whether the left table has matching values;
LEFT JOIN joins tables and returns all rows of data from the left table, regardless of whether there are matching values ​​on the right.

Their grammar rules are as follows:

SELECT column,column,
FROM 表1
RIGHT\LEFT JOIN 表2
ON table1.columns = table2.columns;

 

 

【Example】

Student RIGHT JOIN ON Listudent will return all contents of the latter table,
while
Student LEFT JOIN ON Listudent will return all contents of the previous table.

Run two separate queries to see the difference between the data returned by RIGHT JOIN and LEFT JOIN.

Query 1:

SELECT * FROM student
RIGHT JOIN Listudent  
ON Student.ID = Listudent.ID;

 

 

Query 2:

SELECT * FROM student
LEFT JOIN Listudent  
ON Student.ID = Listudent.ID;

 

 

4. Summary

There is also a FULL JOIN (full join) in SQL, which returns the data of the row as long as there is a match. We can understand it as a combination of RIGHT JOIN and LEFT JOIN. Unfortunately, current database software such as MySQL, Access, and Oracle do not support this syntax.

In addition, people usually call INNER JOIN, RIGHT\LEFT JOIN, FULL JOIN these connection methods as outer joins;
and the connection that matches the conditions directly in the two tables, for example, in the first knowledge point of this section, through Student.ID = Listudent.ID directly joins matching between two tables, this method is called inner join or natural join.

8. Combined query

Combination query cooperation and win-win

1. What is a compound query

【Introduction to knowledge points】

Combined query, also called combined query, compound query, and joint query, is a query used to combine two or more SELECT statements. The content of combined query in different database software will be slightly different. Combined query can combine the results of multiple queries. combined into a result set.

Usually in SQL we will use UNION, UNION ALL, EXCEPT and other keywords to combine multiple SELECT statements to query.

2、UNION

【Introduction to knowledge points】

UNION is an important keyword in a combined query. It can combine two or more SELECT statements, excluding duplicate records.
When using UNION, we should pay attention to one thing:
the number, data type, and order of the columns selected in each SELECT statement must be the same.
The syntax for using UNION is as follows:

SELECT table1.column1, table1.column2 FROM table1
WHERE [clause]
UNION
SELECT table2.column1, table2.column2 FROM table2
WHERE[clause];

 

 

【Example】

Use UNION to do a combined query on the ID and SName of the Student and Listudent tables.
In each SELECT statement, the number, data type, and order of the columns selected for the query must be the same one-to-one.

SELECT student.ID,student.SName FROM student
UNION
SELECT listudent.ID,listudent.SName FROM listudent;

 

 

3、UNION ALL

【Introduction to knowledge points】

The difference between UNION ALL and UNION is that the result returned by UNION ALL contains duplicate records, while the result returned by UNION is not duplicated.
The syntax of UNION ALL is the same as UNION, except that ALL is added to the keyword:

SELECT table1.column1, table1.column2 FROM table1
WHERE [clause]
UNION ALL
SELECT table2.column1, table2.column2 FROM table2
WHERE[clause];

 

【Example】

Use UNION ALL to see how it differs from what UNION returns.
Add the keyword ALL after UNION to see if its results contain duplicate records in both tables.

SELECT student.ID,student.SName FROM student
UNION ALL
SELECT listudent.ID,listudent.SName FROM listudent;

 

4、INTERSECT\EXCEPT

【Introduction to knowledge points】

INTERSECT means intersection. Using the INTERSECT keyword, you can combine two SELECT statements, but only return the same records in the first SELECT statement as in the second SELECT statement. The syntax is equivalent to UNION.
The EXCEPT keyword is different from INTERSECT. It combines two SELECT statements and returns records that are in the first SELECT statement but not in the second SELECT statement.

Currently MySQL5.0 does not support INTERSECT and EXCEPT, while Oracle and SQL Server do.

4. Use ORDER BY in combined queries

【Introduction to knowledge points】

ORDER BY can be used in combined query, but it can only sort the last query result, we cannot use ORDER BY in the sub-statement of combined query.
When sorting the final result, we cannot specify a column to sort, but only use numbers or aliases to define the sorting rules.

【Example】

Query the information of some students whose scores are lower than 25 in the two tables, and sort the results.
Sort the final result, whose collation needs to be referenced by number or alias.

SELECT student.ID,student.SName,student.Credit FROM student
WHERE student.Credit < 25
UNION
SELECT listudent.ID,listudent.SName,listudent.Credit FROM listudent
WHERE listudent.Credit < 25
ORDER BY 1; -- use ORDER BY and quote numbers to sort the results

 

5. Use GROUP BY in combined queries

【Introduction to knowledge points】

GROUP BY is also used for sorting, it can sort the final result, but it can also be used in each clause of a combined query,

【Example】

Using GROUP BY to Score
Each Substatement GROUP BY can be used in every SELECT statement.

SELECT student.ID,student.SName,student.Credit FROM student
WHERE student.Credit < 25
GROUP BY Credit DESC -- score from high to low
UNION
SELECT listudent.ID,listudent.SName,listudent.Credit FROM listudent
WHERE listudent.Credit < 25
GROUP BY Credit; -- score from low to high


summary

1. Summary

【Introduction to knowledge points】

Using composite queries greatly simplifies complex SQL clauses and simplifies the work of retrieving queries from multiple tables.
In this chapter, in addition to combining queries, we also learned about single queries, query operators, subqueries, and table join queries. We need to clarify the usage and logic of each knowledge, which is of great help to our future practice.

Maybe you will ask what is the difference between JOIN and UNION?
First of all, their syntax is very different, UNION has provisions for each SELECT statement query selection, and their functions are also very different;
this time, in terms of process, JOIN is two or more tables After the connection, a new record set is generated for the records that meet the matching conditions, while UNION records the respective tables first, and then merges the records to form a new record set.

 

To be continued below. . . . . .

 

Welcome to visit our official website:

http://www.datanew.com/datanew/homepage

http://www.lechuangzhe.com/homepage

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326268749&siteId=291194637