Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL JOIN the result of UNION

Is it possible to join the result of UNION of two tables with the 3rd table? Something like this:

(SELECT DISTINCT `Fund_ID`, `Fund_Name` FROM `admin` 
    UNION 
SELECT `Fund_ID`,`Fund_Name` FROM `admin_custom` WHERE `admin_custom`.`user_id` = 361)  a
LEFT JOIN `qt1`
ON `qt1`.`Fund ID` = a.`Fund_ID`

but this code doesn't work. I could move JOIN inside of each SELECT query before UNION, but would rather try to JOIN with the UNION result.

How can I fix this?

like image 446
user2723490 Avatar asked Oct 01 '13 07:10

user2723490


People also ask

Is UNION join in MySQL?

The MySQL UNION operator is used to combine the result sets of 2 or more SELECT statements. It removes duplicate rows between the various SELECT statements. Each SELECT statement within the UNION operator must have the same number of fields in the result sets with similar data types.


2 Answers

Yes, it is possible. However, your code is incorrect since you're missing SELECT statement itself, because your first select becomes a rowset (runtime-created table). I.e. you have to specify SELECT operator and fields that you want to get. Simplest case:

SELECT
  a.*
FROM
  (SELECT DISTINCT `Fund_ID`, `Fund_Name` FROM `admin` 
    UNION 
   SELECT `Fund_ID`,`Fund_Name` FROM `admin_custom` WHERE `admin_custom`.`user_id` = 361)  AS a
  LEFT JOIN `qt1`
    ON `qt1`.`Fund ID` = a.`Fund_ID`
like image 181
Alma Do Avatar answered Oct 09 '22 07:10

Alma Do


SELECT * FROM
(SELECT DISTINCT `Fund_ID`, `Fund_Name` FROM `admin` 
    UNION 
SELECT `Fund_ID`,`Fund_Name` FROM `admin_custom` WHERE `admin_custom`.`user_id` = 361)  a
LEFT JOIN `qt1`
ON `qt1`.`Fund ID` = a.`Fund_ID`;
like image 28
Praveen Prasannan Avatar answered Oct 09 '22 07:10

Praveen Prasannan