📜  MySQL Union和Join之间的区别

📅  最后修改于: 2020-11-18 03:22:52             🧑  作者: Mango

MySQL Union和Join之间的区别

Union和Join是用于在关系数据库管理系统(RDBMS)中的多个表上执行操作的SQL子句。它们通过合并两个或多个表中的数据来产生结果。但是,两个子句中组合来自两个或多个关系的数据的方式不同。在进行比较之前,我们将简要讨论这些条款。

什么是联盟条款?

MySQL Union子句允许我们使用多个SELECT查询将两个或多个关系组合到单个结果集中。默认情况下,它具有从结果集中删除重复行的功能。

MySQL中的Union子句必须遵循以下给出的规则:

  • 所有表中列的顺序和数量必须相同。
  • 数据类型必须与每个选择查询的相应位置兼容。
  • SELECT查询中的列名应采用相同的顺序。

句法

SELECT column_name(s) FROM table_name1  
UNION  
SELECT column_name(s) FROM table_name2;

什么是Join子句?

MySQL中的Join与SELECT语句一起使用,以从多个表中检索数据。每当我们需要从多个表中获取记录时,都会执行该操作。它仅返回表中与指定条件匹配的那些记录。

句法

SELECT column_name(s) FROM table_name1   
JOIN table_name2  ON conditions;

联合与加入

让我们使用下面的比较表来讨论Union和Join之间的本质区别。

SN UNION JOIN
1. It is used to combine the result from multiple tables using SQL queries. It is used to fetch the record from more than one table using SQL queries.
2. It combines the records into new rows. It combines the records into new columns.
3. It allows us to connect the tables vertically. It will enable us to join the tables vertically.
4. It works as the conjunction of the more than one tables that sum ups all records. It produces results in the intersection of the tables.
5. In this, the order and number of the columns must be the same in all tables. In this, the order and number of the columns do not need to be the same in all tables.
6. It has a default feature to remove the duplicate rows from the result set. It does not eliminate the duplicate rows from the result set.
7. In this, the data type must be the same in all SELECT statements. In this, there is no need to be the same data type. It can be different.
8. The Union clause is applicable only when the number of columns and corresponding attributes has the same domain. The Join clause is applicable only when the two tables that are going to be used have at least one column.
9. The Union clause can have mainly two types that are given below:
  • Union
  • Union All
The Join clause can have different types that are given below:
  • Inner Join (Sometimes Join)
  • Left Join (Left Outer Join)
  • Right Join (Right Outer Join)
  • Full Join (Outer Join)

现在,我们将借助一个示例来理解它。

联合实例

假设我们的数据库具有以下表格:“ Student1”和“ Student2”包含以下数据:

以下语句通过组合两个表产生包含所有学生姓名和科目的输出。

SELECT stud_name, subject FROM student1  
UNION  
SELECT stud_name, subject FROM student2;  

成功执行后,我们将获得包含所有唯一学生姓名和学科的输出:

加盟实例

假设我们的数据库具有以下表格:“学生”和“技术”包含以下数据:

我们可以使用以下查询从两个表中获取记录:

SELECT students.stud_fname, students.stud_lname, students.city, technologies.technology    
FROM students   
JOIN technologies    
ON students.student_id = technologies.tech_id;

我们将得到以下输出: