Difference between JOIN and UNION in SQL

   Join means that some records with the same conditions in the two tables are connected to generate a recordset, and union means that the two generated recordsets (with the same fields) are combined together to become a new recordset.

1. The difference between JOIN and UNION

Join is that after the two tables are connected, some records with the same conditions in them generate a recordset, and
union is the combination of the two recordsets generated (the fields must be the same) to become a new recordset .

JOIN is used to join two tables according to the ON condition. There are four main types:
INNER JOIN: Inner join records in two tables. Only when at least one row belonging to both tables meets the join condition, the inner join returns rows. What I understand is that as long as a record doesn't meet the ON condition, it won't show up in the result set.
LEFT JOIN / LEFT OUTER JOIN: Outer joins records from two tables and includes all records from the left table. If a record in the left table does not have a matching record in the right table, then all select list columns in the right table are null in the associated result set. It is understood that even if the ON condition is not met, all records in the left table are displayed, and the right table field of this type of record in the result set is null.
RIGHT JOIN / RIGHT OUTER JOIN: Outer joins records in two tables and includes all records in the right table. Simply put, it is the reverse of LEFT JOIN.
FULL JOIN / FULL OUTER JOIN: A full outer join returns all rows from the left and right tables. That is LEFT JOIN and RIGHT JOIN and merge, the data of the left and right tables are all displayed.

2. The basic syntax of JOIN:
Select table1.* FROM table1 JOIN table2 ON table1.id=table2.id
UNION operator

Combines the result sets of two or more queries into a single result set that contains all the rows of all the queries in the union query. The result set column names of UNION are the same as the column names of the result set of the first Select statement in the UNION operator. Result set column names from another Select statement will be ignored.
Two of the different uses are UNION and UNION ALL, the difference is that UNION removes duplicate rows from the result set. If UNION ALL is used all rows will be included and duplicate rows will not be removed.

3. The difference between UNION and UNION ALL:

union checks duplicates
union all does not check. For
example , select 'a' union select 'a' outputs one line a. For
example, select 'a' union all select 'a' outputs two lines a.

Guess you like

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