MySQL UNION where子句条件来自第一个选择

时间:2015-09-02 00:51:16

标签: mysql database

如何联合两个相同表但第二个选择条件的选择取决于第一个选择属性。这是我的查询

SELECT *
FROM tbl_preference_header h
LEFT JOIN tbl_preference_detail d
OJ h.id = d.superid
WHERE h.type = 'CP' 
UNION
SELECT *
FROM tbl_preference_header h2
LEFT JOIN tbl_preference_detail d2
ON h2.id = d2.superid
WHERE h2.type = 'GP' AND d2.cat3code NOT IN (d.cat3code)

我想要的是在第二个select语句中它不包含第一个select语句中的所有cat3code。我的查询中有错误d在第二个select语句中无法识别。

我怎样才能做到这一点?除了工会之外,我可以使用另一种方法吗?

2 个答案:

答案 0 :(得分:4)

您将无法直接引用原始查询,但您可以将原始查询带入子查询,如下所示:

SELECT * FROM tbl_preference_header h left join tbl_preference_detail d on h.id = d.superid where type = 'CP' 

union 

select * 
from 
    tbl_preference_header h2 
        left join tbl_preference_detail d2 on h2.id = d2.superid 
where type = 'GP' and d2.cat3code not in (
    select d.cat3code 
    from 
        tbl_preference_header h 
            left join tbl_preference_detail d on h.id = d.superid 
    where type = 'CP' 
)

答案 1 :(得分:0)

要弄清楚你想要的东西有点难。如果我认为typetbl_preference_detail的一部分,那么您的查询等同于:

SELECT *
FROM tbl_preference_header h left join
     tbl_preference_detail d
     on h.id = d.superid
WHERE d.type = 'CP'  or
      (d.type = 'GP' and
       not exists (select 1
                   from tbl_preference_detail d2
                   where d2.cat3code = d.cat3code and
                         d2.type = 'CP'
                  )
      )