SQL WHERE IN 子句中的多个键

Use*_*rol 5 sql row-value-expression

假设您有Accounts一个表,其中ID列是 PK 并且TaxID+AccountNumber是唯一约束:

select * from Accounts where ID in (100, 101)
Run Code Online (Sandbox Code Playgroud)

现在您想使用自然键进行类似的查询:

select * from Accounts 
where {TaxID, AccountNumber} in 
  ({"0123456", "2000897"}, {"0125556", "2000866"})
Run Code Online (Sandbox Code Playgroud)

所以这涉及元组并且看起来非常合法。是否可以用 ANSI SQL 来表达?也许在某些特定的 SQL 扩展中?如果不是,为什么(欢迎任何猜测)?

ype*_*eᵀᴹ 3

这两者都是有效的 ISO/ANSI 完整 SQL-92 语法:

SELECT a.* 
FROM Accounts a
  INNER JOIN
    ( VALUES('0123456', '2000897'), ('0125556', '2000866')
    ) AS v(TaxID, AccountNumber) 
  ON (a.TaxID, a.AccountNumber) = (v.TaxID, v.AccountNumber)

SELECT * 
FROM Accounts a
WHERE (a.TaxID, a.AccountNumber) IN 
    ( VALUES ('0123456', '2000897'), ('0125556', '2000866') )
Run Code Online (Sandbox Code Playgroud)

但我认为它们都不适用于当前的任何 DBMS。


这也是有效的完整 SQL-92 语法(由于以下原因,它在 SQL-Server 2008 中不起作用NATURAL JOIN):

SELECT a.* 
FROM Accounts a
  NATURAL JOIN
    ( VALUES('0123456', '2000897'), ('0125556', '2000866')
    ) AS v(TaxID, AccountNumber) 
Run Code Online (Sandbox Code Playgroud)

这也是有效的 SQL(不确定它是否在 92 规范或更高版本中) - 并且就是您所拥有的(但使用括号,而不是大括号)。
MySQL、Postgres、DB2 支持(但 SQL Server 不支持):

SELECT a.* 
FROM Accounts a
WHERE (TaxID, AccountNumber) IN
    ( ('0123456', '2000897'), ('0125556', '2000866') )
  ;
Run Code Online (Sandbox Code Playgroud)

DBA.SE 中也有类似的问题,有各种其他方法来表达这个问题:
选择两列在集合中的位置