我目前想要将两个SQL查询合并为一个。这有点类似于SQL: Taking the result of of query and using it another - 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
结果是错误:标量子查询只允许返回单行,我应该如何将“=”替换为“IN”?或者我的陈述完全错了?
答案 0 :(得分: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
答案 1 :(得分:0)
“将两个查询合并为一个” - 这不是一个好的规范。尝试找出你想要作为FLAT二维表得到的确切内容,将嵌套的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]