📜  SQL |联合条款

📅  最后修改于: 2021-05-20 06:49:21             🧑  作者: Mango

Union子句用于合并两个单独的select语句,并产生结果集,作为两个select语句的并集。
笔记:

  1. 两个select语句中要使用的字段必须具有相同的顺序,相同的编号和相同的数据类型。
  2. Union子句在结果集中产生不同的值,以获取重复的值,也必须使用UNION ALL而不是UNION。

基本语法:

SELECT column_name(s) FROM table1 UNION SELECT column_name(s) FROM table2;

Resultant set consists of distinct values.
SELECT column_name(s) FROM table1 UNION ALL SELECT column_name(s) FROM table2;

Resultant set consists of duplicate values too.

表格1

表12

查询

  • 要从Student和Student_Details表中获取不同的ROLL_NO。
    SELECT ROLL_NO FROM Student UNION SELECT ROLL_NO FROM Student_Details; 
    

    输出:

    ROLL_NO
    1
    2
    3
    4
  • 要从Student和Student_Details表中获取ROLL_NO,包括重复值。
    SELECT ROLL_NO FROM Student UNION ALL SELECT ROLL_NO FROM Student_Details; 
    

    输出:

    ROLL_NO
    1
    2
    3
    4
    3
    2
  • 要从学生表WHERE ROLL_NO大于3并从ROLL_NO中获取NAME,请从Student_Details表WHERE ROLL_NO小于3中获取ROLL_NO,包括重复值,最后按ROLL_NO对数据进行排序。
    SELECT ROLL_NO,NAME FROM Student WHERE ROLL_NO>3 
    UNION ALL
    SELECT ROLL_NO,Branch FROM Student_Details WHERE ROLL_NO<3
    ORDER BY 1; 
    
    Note:The column names in both the select statements can be different but the
     data type must be same.And in the result set the name of column used in the first
     select statement will appear. 
    

    输出:

    ROLL_NO NAME
    1 Information Technology
    2 Computer Science
    4 SURESH