using tuples in sql in clause

前端 未结 3 2018
夕颜
夕颜 2020-12-05 20:42

Given a database like this:

BEGIN TRANSACTION;
CREATE TABLE aTable (
a STRING,
b STRING);
INSERT INTO aTable VALUES(\'one\',\'two\');
INSERT INTO aTable VALU         


        
相关标签:
3条回答
  • 2020-12-05 20:55

    you can use a join:

    SELECT aTable.a, aTable.b FROM aTable
    JOIN anotherTable ON aTable.a = anotherTable.a AND aTable.b = anotherTable.b
    
    0 讨论(0)
  • 2020-12-05 20:58

    Another alternative is to use concatenation to make your 2-tuple into a single field :

    SELECT a,b FROM aTable
    WHERE (aTable.a||'-'||aTable.b) IN
    (SELECT (anotherTable.a || '-' || anotherTable.b FROM anotherTable);
    

    ...just be aware that bad things can happen if a or b contain the delimiter '-'

    0 讨论(0)
  • 2020-12-05 21:06

    your code works if you do it in PostgreSQL or Oracle. on MS SQL, it is not supported

    use this:

    SELECT a,b FROM aTable
    WHERE 
    -- (aTable.a,aTable.b) IN -- leave this commented, it makes the intent more clear
    EXISTS
    (
        SELECT anotherTable.a,anotherTable.b -- do not remove this too, perfectly fine for self-documenting code, i.e.. tuple presence testing
        FROM anotherTable
        WHERE anotherTable.a = aTable.a AND anotherTable.b = aTable.b
    );
    

    [EDIT]

    sans the stating of intent:

    SELECT a,b FROM aTable
    WHERE     
    EXISTS
    (
        SELECT *
        FROM anotherTable
        WHERE anotherTable.a = aTable.a AND anotherTable.b = aTable.b
    );
    

    it's somewhat lame, for more than a decade, MS SQL still don't have first-class support for tuples. IN tuple construct is way more readable than its analogous EXISTS construct. btw, JOIN also works (tster's code), but if you need something more flexible and future-proof, use EXISTS.

    [EDIT]

    speaking of SQLite, i'm dabbling with it recently. yeah, IN tuples doesn't work

    0 讨论(0)
提交回复
热议问题