SQL operation result set - union, difference, intersection, result set sorting

In order to cooperate with the test, two tables were specially built, and some test data were added, in which the characters of Soochow were repeatedly recorded.

  Table: Person_1 Wei Guo characters

   

  Table: Person_2 People in Shu Kingdom

  

  A. Union forms union

    Union can join two or more result sets to form a "union". All records in the subresult set are grouped together to form a new result set.

     1. Restrictions

     If you use Union to join the result set, there are 4 qualifications.

     (1) The sub-result sets must have the same structure.

     (2) The number of columns in the word result set must be the same.

     (3) The data types corresponding to the sub-result sets must be compatible.

     (4) Each sub-result set cannot contain order by and compute clauses.

     2. Grammatical form

    select_statement union [all] select_statement

   all means that the final result set will contain all the rows, and duplicate rows cannot be deleted.

    Example:

  SELECT Name FROM Person_1
  UNION
  SELECT Name FROM Person_2

   The result generated is:

   

  Noticing the duplicate records, Sun Quan and Zhou Yu only showed one. Let's replace UNION with UNION ALL to see what the result is:

  SELECT Name FROM Person_1
  UNION ALL
  SELECT Name FROM Person_2

  注意到重复记录,孙权与周瑜出现了两次,这就是UNION ALL 与 UNION的不同之处。

  

   B、Except形成差集

   Except可以对两个或多个结果集进行连接,形成“差集”。返回左边结果集合中已经有的记录,而右边结果集中没有的记录。

   限定条件:

    1、子结果集要具有相同的结构。

    2、子结果集的列数必须相同。

    3、子结果集对应的数据类型必须可以兼容。

    4、每个子结果集不能包含order by 和 compute子句。

    语法形式:

    select_statement except select_statement 

    自动删除重复行。

    示例:

  SELECT Name FROM Person_1
  EXCEPT
  SELECT Name FROM Person_2

    结果:

    

    留意到表Person_2有的,孙权周瑜已被去除。

  C、InterSect形成交集

    InterSect可以对两个或多个结果集进行连接,形成“交集”。返回左边结果集和右边结果集中都有的记录。

  1、限定条件  

    要是用Except来连接结果集,有4个限定条件。

    (1)、子结果集要具有相同的结构。

    (2)、子结果集的列数必须相同。

    (3)、子结果集对应的数据类型必须可以兼容。

    (4)、每个子结果集不能包含order by或compute子句。

  2、语法形式

  select_statement intersect select_statement        

  示例:

  SELECT Name FROM Person_1
  INTERSECT
  SELECT Name FROM Person_2

   返回的结果如下:

   

   留意到只取两张表都有的记录(周瑜,孙权),这就是所谓的交集。

  D、结果集的排序

  SELECT Name FROM Person_1
  INTERSECT
  SELECT Name FROM Person_2
  ORDER BY Name DESC    --此处的字段名相同了,如果不同,请切记排序列名,只能够是第一个表的列名

  这里只有两点要注意

  1.ORDER BY是对整个运算后的结果排序,并不是对单个数据集。

  2.ORDER BY后面排序的字段名称是第一个数据集的字段名或者别名。

 

转自:http://www.cnblogs.com/kissdodog/archive/2013/06/24/3152743.html

Guess you like

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