[SQL] Union (UNION), intersection (INTERSECT), difference (minus), removal (EXCEPT)

UNION

Query the student number, course number and grades of students who have taken course No. 180101 or No. 180102 or both.

( SELECT 学号, 课程号, 成绩 FROM 学习 WHERE 课程号= '180101' ) 
UNION
( SELECT 学号, 课程号, 成绩 FROM 学习 WHERE 课程号= '180102' )

Unlike the SELECT clause, the UNION operation automatically removes duplicates.
In this example, if only the student's student ID is output, the same student ID will appear only once. If you want to keep all repetitions, you must use UNION ALL instead of UNION, and the number of repeated tuples in the query result is equal to the sum of the number of repeated tuples in the two sets.

The difference between UNION and UNION ALL

Conclusion:
union removes duplication and sorts, union all directly returns the merged result without deduplication or sorting;
union all has better performance than union;

INTERSECT

Query the student number, course number and grades of students who have taken courses 180101 and 180102 at the same time.

( SELECT 学号, 课程号, 成绩 FROM 学习 WHERE 课程号= '180101' ) 
INTERSECT
( SELECT 学号, 课程号, 成绩 FROM 学习 WHERE 课程号= '180102' )

The INTERSECT operation automatically removes repetitions. If you want to keep all repetitions, you must use INTERSECT ALL instead of INTERSECT. The number of repeated tuples in the result is equal to the lesser number of repeated tuples in the two sets.

The intersect operation returns the same part of the query results as their intersection

minus (oracle)

Return the row records that are not the same as the second query result in the first query result,
that is, the difference set of the two results

SELECT * FROM abc2 
minus 
SELECT * FROM abc;

EXCEPT

Query the student number, course number and grades of the students who have taken the course No. 180101 but have not taken the course No. 180102.

( SELECT 学号, 课程号, 成绩 FROM 学习 WHERE 课程号= '180101' ) 
EXCEPT
( SELECT 学号, 课程号, 成绩 FROM 学习 WHERE 课程号= '180102' )

The EXCEPT operation automatically removes repetitions. If you want to keep all repetitions, you must replace EXCEPT with EXCEPT ALL. The number of repeated tuples in the result is equal to the difference between the number of repeated tuples in the two sets (provided that the difference is positive).
In a DBMS that does not support INTERSECT and EXCEPT operations, other methods must be used, among which nested query is a very effective method.

Guess you like

Origin blog.csdn.net/qq_44033208/article/details/131856124