5

让我们看一下完美运行的 Oracle SQL 示例:

样本数据:

SQL> create table test (a number, b number);
SQL> insert into test values(1, 1);
SQL> insert into test values(1, 2);
SQL> insert into test values(1, 3);
SQL> insert into test values(1, 4);
SQL> insert into test values(1, 5);
SQL> insert into test values(2, 1);
SQL> insert into test values(2, 2);
SQL> insert into test values(2, 3);
SQL> insert into test values(2, 4);
SQL> insert into test values(2, 5);
SQL> insert into test values(4, 1);

SQL> select * from test;

         A          B
---------- ----------
         1          1
         1          2
         1          3
         1          4
         1          5
         2          1
         2          2
         2          3
         2          4
         2          5
         4          1

询问:

SQL> select * from test where (a, b) in (select 1, 4 from dual);

         A          B
---------- ----------
         1          4

这是 sql-fiddle:http ://www.sqlfiddle.com/#!4/8375e/3/0

简单的问题:上面的“where (a, b)”子句在 MS SQL 中是否有任何等价物?我一直在谷歌、MS Docs 中四处寻找,到目前为止什么都没有……

4

2 回答 2

5

虽然 SQL Server 有一个Table Value Constructor可用于某些用例的,但 SQL Server 不支持 SQL 标准行值表达式和从行值表达式派生的谓词以供一般使用(目前)。您将不得不诉诸使用等效EXISTS子句的半连接子查询:

这个:

select * from test where (a, b) in (select 1, 4 from dual);

相当于这个(参见SQLFiddle 演示):

select * from test where exists (
  select * from (
    select 1, 4 -- Replace with "real" subselect
  ) t(a, b)
  where test.a = t.a and test.b = t.b
)

或者,更一般地说,通过使用公共表表达式(参见SQLFiddle 演示):

with t(a, b) as (
  select 1, 4 -- Replace with "real" subselect
)
select * from test where exists (
  select * from t
  where test.a = t.a and test.b = t.b
)
于 2013-04-11T07:04:09.700 回答
0

下面的查询怎么样,它在 sql server 中支持;我猜想a=1 and b=4在 sql server 中给出与 oracle 查询相同的结果。:

select 
    * 
from 
    test 
where 
    a=1 and 
    b=4;
于 2013-04-11T06:56:56.543 回答