How can I rewrite a multi-column IN clause to work on SQLite?

前端 未结 3 1486
后悔当初
后悔当初 2020-12-09 04:02

I\'ve got a query that looks something like this:

SELECT
  *
FROM table
WHERE
  (col1, col2) in (
    (\'col1_val1\', \'col2_val1\'),
    (\'col1_val2\', \'c         


        
3条回答
  •  孤城傲影
    2020-12-09 04:41

    In sqlite try to add the VALUES keyword:

    SELECT *
    FROM table
    WHERE
      (col1, col2) in ( VALUES     --> add this keyword and remove the last ,
        ('col1_val1', 'col2_val1'),
        ('col1_val2', 'col2_val2'),
        ('col1_val3', 'col2_val3')
      )
    

    Basically in sqLite executing the query:

    VALUES
    ('col1_val1', 'col2_val1'),
    ('col1_val2', 'col2_val2');
    

    is the same as:

    SELECT 'col1_val1' AS column1, 'col2_val1' AS column2
    UNION 
    SELECT 'col1_val2' AS column1, 'col2_val2' AS column2;
    

    or combined:

    SELECT 'col1_val1' AS column1, 'col2_val1' AS column2
    UNION  VALUES  ('col1_val2', 'col2_val2');
    

    So you could even write it like:

    SELECT * 
      FROM table
      WHERE (col1, col2) IN ( 
          SELECT 'col1_val1', 'col2_val1'
          UNION 
          SELECT 'col1_val2', 'col2_val2'
      );
    

    which is a simple subquery and works in all/most databases.

提交回复
热议问题