Suppose you have these tables:
Table Name: Salesman
Fields: S_ID(Primary Key), Name
Table Name: Region_1
Fields: Reg_ID(Primary Key), S_ID(Foreign Key), sales
Table Name: Region_2
Fields: Reg_ID(Primary Key), S_ID(Foreign Key), sales
Table Name: Region_3
Fields: Reg_ID(Primary Key), S_ID(Foreign Key), sales
Table Name: Region_4
Fields: Reg_ID(Primary Key), S_ID(Foreign Key), sales
Query 1: Find out total of sales of each salesman in all the regions.
Query 2: Find out total of sales of a particual salesman in all the regions. (if the first one is solved I think this will be easy. 🙂 )
Query 1: Find out total of sales of each salesman in all the regions.
Use:
Query 2: Find out total of sales of a particual salesman in all the regions.
Add the WHERE clause to the query above:
…replace the
?with the salesperson’s s_id value.The Lesson: UNION vs UNION ALL
UNIONandUNION ALLwill allow you to combine two queries, but they have to have the same data types in the column positions. For example, say query one returns data types in the following order:Any subsequent query that is union’d to the first has to return the same data types in the same position. Pay special attention to the fact of data types – it doesn’t guarantee the data within the column.
The second issue to UNIONs is knowing the difference between
UNIONandUNION ALL.UNIONwill remove duplicates if they exist (equivalent to usingDISTINCT), which is not desired in the given scenario.UNION ALLwill not remove duplicates, and is faster because of this.