7

是否可以在SQL 查询的子句中比较元组(谢谢,a_horse_with_no_name) ?WHERE这样,我可以转换它:

/* This is actually a sub-sub-sub-query in the middle *
 * of an incredibly complex stored procedure.         */
SELECT ISNULL(SUM(DT.DetailField), 0)
FROM   DetailTable DT
WHERE  DT.ForeignKey = ...
AND    EXISTS (/* I know this sub-sub-sub-sub-query *
                * will return at most one row.      */
               SELECT 'X'
               FROM   HeaderTable HT
               WHERE  HT.HeaderKey    = DT.HeaderKey
               AND    HT.HeaderField1 = ...
               AND    HT.HeaderField2 = ...)

变成类似这样的东西:

SELECT ISNULL(SUM(DetailField), 0)
FROM   DetailTable DT
WHERE  DT.ForeignKey = ...
AND    (SELECT HT.HeaderField1, HT.HeaderField2
        FROM   HeaderTable HT
        WHERE  HT.HeaderKey = DT.HeaderKey) = (..., ...)
4

4 回答 4

5

写作

AND(选择 HT.HeaderField1,HT.HeaderField2
        FROM HeaderTable HT
        WHERE HT.HeaderKey = DT.HeaderKey) = (..., ...)

当然是可能的。至少对于 Oracle 和 PostgreSQL

如果您不确定子选择是否返回多行,您甚至可以=IN

于 2011-02-04T16:41:46.207 回答
5

您正在寻找的是内部连接:

SELECT ISNULL(SUM(DetailField), 0)
FROM   DetailTable DT
INNER JOIN HeaderTable HT ON HT.HeaderKey = DT.HeaderKey
WHERE  DT.ForeignKey = ...
AND    HT.HeaderField1 = ...
AND    HT.HeaderField2 = ...)
于 2011-02-04T16:46:06.233 回答
2

似乎您正在尝试比较记录而不是此处的表格。事实上,您正在比较查询的结果

Oracle 和 MySQL 完全可以。以下查询是有效的并且可以完成工作:

SELECT (SELECT foo, bar FROM wathever) = (SELECT fuu, baz FROM another);

它会将字段一一进行比较,如果它们都匹配则返回 1(如果不匹配则返回 0)。如果子查询返回多于一行,则会引发 SQL 错误。该表达式也可以在其他地方使用,如在 WHERE 子句中。

postgreSQL 更新

正如@tsionyx 指出的那样,在PostgreSQL 中,子查询不能返回多个列。返回行值类型是可行的:

SELECT (SELECT ROW(foo, bar) FROM wathever) = (SELECT ROW(fuu, baz) FROM another);
于 2011-02-04T16:58:20.340 回答
1

Goran 的回答对我来说是最好的,我投了赞成票。只是添加另一个选项,因为您使用的是 SQL Server,所以从子查询中获取多个列的灵活方法是outer apply. 您可以比较两个值(元组),例如:

select  *
from    SomeTable t1
outer apply
        (
        select  *
        from    SomeOtherTable t2
        where   t1.Stuff = t2.Unit
        ) sub1
outer apply
        (
        select  *
        from    YetAnotherTable t3
        where   t1.Stuff = t3.jetser
        ) sub2
where   sub1.col1 = sub2.col1
        and sub1.col2 = sub2.col2
于 2011-02-04T22:46:50.503 回答