Association query in sql

EXCEPT, INTERSECT usage in SQL
                       EXCEPT returns the difference between two result sets (that is, returns all distinct values ​​not found by the right query from the left query).
                       INTERSECT returns the intersection of two result sets (that is, all distinct values ​​returned by both queries).

                      UNION returns the union of two result sets.

      UNION, EXCEPT, and INTERSECT keywords are used for querying collections. Their functions are:
      UNION: combine the result sets of two or more SELECT statements and remove duplicate results;
      UNIONALL: combine two or more SELECT statements EXCEPT: query the results
      contained in the result set of the A statement but not in the result set of the B statement;
syntax:
{ (<SQL-query statement 1>) }
{ EXCEPT | INTERSECT }
{ (<SQL-query statement 2>)}

Restrictions
(1) The number and order of columns in all queries must be the same.
(2) The column data types in the two query result sets to be compared can be different but must be compatible.
(3) The two query result sets being compared cannot contain columns of incomparable data types (xml, text, ntext, image or non-binary CLR user-defined types).
(4) The column names of the returned result set are the same as those returned by the query on the left side of the operand. Column names or aliases in the ORDER BY clause must refer to the column names returned by the left-hand query.
(5) Cannot be used with the COMPUTE and COMPUTE BY clauses.
(6) When determining distinct values ​​by comparing rows, two NULL values ​​are considered equal. (The nullability of any column in the result set returned by EXCEPT or INTERSECT is the same as the nullability of the corresponding column returned by the query to the left of the operand.)
Execution order when used with other operators in expressions
1. Parentheses expression
2, INTERSECT operand
3, EXCEPT and UNION that are evaluated from left to right based on the position in the expression
If EXCEPT or INTERSECT are used to compare more than two querysets, the data type conversion is by a single comparison It is determined by two queries and follows the expression evaluation rules mentioned earlier.

Example:
tableA tableB

NULL NULL
NULL 2
1 3
1 4
2 5
3 5
4
5
A: (SELECT * FROM TableA) EXCEPT (SELECT * FROM TableB)
Result: 1
(1 row(s) affected)
B: SELECT * FROM TableA INTERSECT SELECT * FROM TableB
Result: 2
   3
   4
   5
    (4 row(s) affected)

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326613590&siteId=291194637