10

是否可以将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结果。

我怎样才能解决这个问题?

4

2 回答 2

14

对的,这是可能的。但是,您的代码不正确,因为您缺少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`
于 2013-10-01T07:53:16.523 回答
3
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`;
于 2013-10-01T07:51:25.697 回答