如何将UNION查询视为子查询

时间:2011-03-09 00:28:31

标签: sql db2 subquery union

我有一组表,逻辑上是出于性能原因将一个表拆分成多个表。我需要编写一个有效地将所有表连接在一起的查询,因此我使用结果的单个where子句。我已成功使用UNION对每个子表明确使用WHERE子句的结果,如下所示

SELECT * FROM FRED_1 WHERE CHARLIE = 42
UNION 
SELECT * FROM FRED_2 WHERE CHARLIE = 42
UNION 
SELECT * FROM FRED_3 WHERE CHARLIE = 42

但是因为有十个单独的子表每次更新WHERE子句都很痛苦。我想要的是这样的东西

SELECT * 
FROM (
    SELECT * FROM FRED_1 
    UNION 
    SELECT * FROM FRED_2 
    UNION 
    SELECT * FROM FRED_3) 
WHERE CHARLIE = 42

如果它有所不同,则需要针对DB2数据库运行查询。

这是我需要做的更全面(消毒)的版本。

select * 
from ( select * from FRD_1 union select * from FRD_2 union select * from FRD_3 ) as FRD, 
     ( select * from REQ_1 union select * from REQ_2 union select * from REQ_3 ) as REQ, 
     ( select * from RES_1 union select * from RES_2 union select * from RES_3 ) as RES 
where FRD.KEY1 = 123456
  and FRD.KEY1 = REQ.KEY1
  and FRD.KEY1 = RES.KEY1
  and REQ.KEY2 = RES.KEY2

新信息:

看起来这个问题更多地与联合中的字段数量有关。如果我大大限制了字段,我可以获得以下大部分语法变体。不幸的是,限制这些字段意味着最终的查询,虽然可能有用,但并没有给我我想要的结果。除了2个键之外,我还设法从其中一个表中获得了另外3个字段。不止于此,查询失败。

5 个答案:

答案 0 :(得分:30)

我相信你必须给你的子查询结果命名。我不知道db2所以我在黑暗中拍摄,但我知道这可以在其他几个平台上使用。

SELECT * 
FROM (
    SELECT * FROM FRED_1 
    UNION 
    SELECT * FROM FRED_2 
    UNION 
    SELECT * FROM FRED_3) AS T1
WHERE CHARLIE = 42

答案 1 :(得分:2)

如果逻辑实现是单个表但物理实现是多个表,那么如何创建定义逻辑模型的视图。

CREATE VIEW VW_FRED AS 
SELECT * FROM FRED_1 
UNION    
SELECT * FROM FRED_2 
UNION    
SELECT * FROM FRED_3

那么这是一个简单的问题

SELECT * FROM VW_FRED WHERE CHARLIE = 42

同样,我不熟悉db2语法,但这给了你一般的想法。

答案 2 :(得分:1)

我不熟悉DB2语法,但为什么你不是INNER JOINLEFT JOIN呢?

SELECT * 
  FROM FRED_1
 INNER JOIN FRED_2
    ON FRED_1.Charlie = FRED_2.Charlie
 INNER JOIN FRED_3
    ON FRED_1.Charlie = FRED_3.Charlie
 WHERE FRED_1.Charlie = 42

如果 FRED_2 FRED_3 中不存在这些值,请使用LEFT / OUTER JOIN。我假设 FRED_1 是主表,如果存在记录,那么它将在此表中。

答案 3 :(得分:0)

with 
FRD as ( select * from FRD_1 union select * from FRD_2 union select * from FRD_3 ), 
REQ as ( select * from REQ_1 union select * from REQ_2 union select * from REQ_3 ), 
RES as ( select * from RES_1 union select * from RES_2 union select * from RES_3 )
SELECT * from FRD, REQ, RES 
WHERE FRD.KEY1 = 123456
and FRD.KEY1 = REQ.KEY1
and FRD.KEY1 = RES.KEY1
and REQ.KEY2 = RES.KEY2

答案 4 :(得分:0)

也许:

SELECT * FROM 
(select * from FRD_1 
union 
select * from FRD_2 
union 
select * from FRD_3) FRD
INNER JOIN (select * from REQ_1 union select * from REQ_2 union select * from REQ_3) REQ
  on FRD.KEY1 = REQ.KEY1
INNER JOIN (select * from RES_1 union select * from RES_2 union select * from RES_3) RES
  on FRD.KEY1 = RES.KEY1
WHERE FRD.KEY1 = 123456 and REQ.KEY2 = RES.KEY2