0

我目前想将两个 SQL 查询合二为一。这有点类似于SQL:获取查询的结果并使用它另一个 - combine。假设有两个查询:

SQL 语句

1.) SELECT * 
    FROM (SELECT B.example1  
          FROM EXAMPLE1A A  
          INNER JOIN EXAMPLE1B B ON A.ID = B.ID  
          WHERE A.ABC ='ABC' 
          ORDER BY A.ORDER_BY ) as colstate

2.) SELECT colstate 
    FROM EXAMPLE_TABLE 
    WHERE EFG LIKE '%' 
      AND BGTHAN >= '1' 
      AND SMTHAN <= '100' 
    ORDER BY ORDER_BY ASC

我想使用查询 1.) 中的结果作为查询 2.) 中的 colstate(列语句)。但:

我试过的是:

SELECT (SELECT B.example1  
        FROM EXAMPLE1A A  
        INNER JOIN EXAMPLE1B B 
           ON A.ID = B.ID  
        WHERE A.ABC ='ABC' 
        ORDER BY A.ORDER_BY ) 
FROM EXAMPLE_TABLE 
WHERE EFG LIKE '%' 
  AND BGTHAN >= '1' 
  AND SMTHAN <= '100' 
ORDER BY ORDER_BY ASC

结果是Error: Scalar subquery is only allowed to return a single row,我应该如何将“=”替换为“IN”?还是我的说法完全错误?

4

2 回答 2

0

该错误表示您用作列语句的查询最多只能返回一行。

它应该看起来像这样:

SELECT (SELECT B.example1  
        FROM EXAMPLE1A A  
        INNER JOIN EXAMPLE1B B 
           ON A.ID = B.ID  
        WHERE A.ABC ='ABC' 
          AND A.SOME_COLUMN = E.SOMECOLUMN // retrieve only relevant data for this row
        ORDER BY A.ORDER_BY ) 
FROM EXAMPLE_TABLE E 
WHERE EFG LIKE '%' 
  AND BGTHAN >= '1' 
  AND SMTHAN <= '100' 
ORDER BY ORDER_BY ASC
于 2013-11-07T07:48:12.313 回答
0

“将两个查询合二为一”——这不是一个好的规范。尝试找出您想要获得的 FLAT 二维表究竟是什么,将嵌套 SELECT 视为嵌套循环,其中内部的 SELECT 只能为父行设置一个值。像这样:

[Outer loop - parent row]
    [Inner loop - children rows]
        // all you can do here is change a single parent's field to anything
        // like constant/sum/avg/topmost/ugly-subquery-returning-a-single-result
    [/Inner loop]
[/Outer loop]
于 2013-11-07T08:09:30.073 回答