2

您如何在查询中引用从外部联接创建的“组合实体”?具体如何替换“??” 在下面的查询中:

SELECT TableA.x, 
       ??.y --How do you select from the combined entity?
  FROM TableA, 
       TableB buys 
FULL OUTER JOIN TableB sells ON buys.run_id = sells.run_id 
                            AND buys.specie_id = sells.specie_id 
                            AND buys.account_id = sells.account_id
WHERE TableA.id = ?? 
  AND -- want to join this with the "combined entity" resulting from the outer join
      buys.buy = 'Y' 
  AND -- Is this valid or does this have to be within the Outer join statement?
      sells.buy = 'N';
4

3 回答 3

3
select TableA.x, fullTable.y 
from TableA 
  INNER JOIN
    ( SELECT y
        FROM TableB buys
          full outer join TableB sells
            on buys.run_id = sells.run_id
            and buys.specie_id = sells.specie_id
            and buys.account_id = sells.account_id
            AND buys.buy = 'Y' AND sells.buy = 'N'    
    ) AS fullTable
    ON TableA.id = fullTable.y

条件可以是最终的WHEREON像这样,但它基本上取消了完全连接:

select TableA.x, fullTable.y 
from TableA 
  INNER JOIN
    ( SELECT y
           , buys.buy AS buysBuy             --- fields here so they can be
           , sells.buy AS sellsBuy           --- used in the final WHERE or ON
        FROM TableB buys
          full outer join TableB sells
            on buys.run_id = sells.run_id
            and buys.specie_id = sells.specie_id
            and buys.account_id = sells.account_id                
    ) AS fullTable
    ON TableA.id = fullTable.y
    AND buysBuy = 'Y' AND sellsBuy = 'N'    --- the condition here
于 2011-06-21T14:52:05.397 回答
2

大概您要问的是如何在查询的其他部分引用连接中使用的列。本身没有联合实体;您仍然必须引用表中的列(在本例中为“买入”或“卖出”,只是碰巧在连接中使用的列对于两个表具有相同的值。

如果你想要哪个不为空(因为这是一个完整的外连接),你可以使用coalesceornvl来查找非空值:

SELECT TableA.x, 
       nvl(buys.run_id,sells.run_id) as run_id,
       ...
于 2011-06-21T14:54:31.593 回答
1

您需要外连接内的sells.buy = 'N'and谓词。buys.buy = 'Y'

SELECT TableA.x, 
       ??.y --How do you select from the combined entity?
  FROM TableA, 
INNER JOIN TableB buys ON <whatever>
                      AND buys.buy = 'Y' 
FULL OUTER JOIN TableB sells ON buys.run_id = sells.run_id 
                            AND buys.specie_id = sells.specie_id 
                            AND buys.account_id = sells.account_id
                            AND sells.buy = 'N'

至于??.y,您需要指定您想要从哪个表中获取它TableA-buysell.

于 2011-06-21T14:56:11.183 回答