MySQL加入UNION的结果

时间:2013-10-01 07:48:34

标签: mysql sql join union

是否可以将两个表的UNION的结果与第三个表联系起来?像这样:

(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`

但此代码不起作用。我可以在JOIN之前在SELECT个查询中移动UNION,但宁愿尝试使用JOIN结果UNION

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:7)

是的,有可能。但是,您的代码不正确,因为您缺少SELECT语句本身,因为您的第一个选择变为行集(运行时创建的表)。即您必须指定要获取的SELECT运算符和字段。最简单的情况:

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`

答案 1 :(得分:2)

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`;