The difference between join and union

1:-A join selects columns from 2 or more tables. 
2:-A union selects rows


Union : The union operator combines the results of two or 

more queries into a single result set. But 
no.of columns 
must match in both/all the queries (and also the order) 

which are used for union. 


Joins: Joins are used to extract information from more than 

one table based on the related column/
coloums (PK and RFK)
any no.

 

JOIN:
A Join is used for displaying columns with the same or different names from different tables. The output displayed will have all the columns shown individually. i.e. The columns will be aligned next to each other.
UNION:
The UNION set operator is used for combining data from two tables which have columns with the same datatype. When a UNION is performed the data from both tables will be collected in a single column having the same datatype.
For eg:
See the two tables shown below:
Table t1
Articleno article price manufacturer_id
1 hammer 3 $ 1
2 screwdriver 5 $ 2
Table t2
manufacturer_id manufacturer
1 ABC Gmbh
2 DEF Co KG
Now for performing a JOIN type the query shown below
SELECTarticleno, article, manufacturer
FROM t1 JOIN t2 ON (t1.manufacturer_id = 
t2.manufacturer_id);
articelno article manufacturer
1 hammer ABC GmbH
2 screwdriver DEF Co KG
That is a join.
UNION means that you have to tables or resultset with the same amount and type of columns and you add this to tables/resultsets together. Look at this example:
Table year2006
Articleno article price manufacturer_id
1 hammer 3 $ 1
2 screwdriver 5 $ 2
Table year2007
Articleno article price manufacturer_id
1 hammer 6 $ 3
2 screwdriver 7 $ 4
SELECTarticleno, article, price, manufactruer_id
FROM year2006
UNION
SELECTarticleno, article, price, manufacturer_id
FROM year2007
articleno article price manufacturer_id
1 hammer 3 $ 1
2 screwdriver 5 $ 2
1 hammer 6 $ 3
2 screwdriver 7 $ 4

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章