如何重写多列IN子句以使用SQLite?

时间:2012-05-09 23:55:33

标签: sqlite

我的查询看起来像这样:

SELECT
  *
FROM table
WHERE
  (col1, col2) in (
    ('col1_val1', 'col2_val1'),
    ('col1_val2', 'col2_val2'),
    ('col1_val3', 'col2_val3'),
  )

这适用于MySQL,但在sqlite3中失败并出现语法错误:

Error: near ",": syntax error

如何将此查询重写为适用于sqlite3的等效查询?

3 个答案:

答案 0 :(得分:10)

选择您喜欢的版本:

http://sqlfiddle.com/#!5/6169b/9

使用临时表

CREATE TEMPORARY TABLE pair (a INTEGER, b INTEGER);
INSERT INTO pair (a, b) VALUES (1, 1);
INSERT INTO pair (a, b) VALUES (2, 2);
....

数据IN对;如果对(a,b)不是唯一的

SELECT *
FROM data
WHERE EXISTS (
  SELECT NULL
  FROM  pair
  WHERE pair.a = data.a
    AND pair.b = data.b
);

数据IN对;如果对(a,b)是唯一的

SELECT     data.*
FROM       data
INNER JOIN pair
        ON pair.a = data.a
       AND pair.b = data.b;

数据不是成对的;如果对(a,b)是唯一的

SELECT    data.*
FROM      data
LEFT JOIN pair
   ON pair.a = data.a
  AND pair.b = data.b
WHERE pair.a IS NULL
   OR pair.b IS NULL;

使用内联表

数据IN对;如果对(a,b)不是唯一的

SELECT *
FROM data
WHERE EXISTS (
  SELECT NULL
  FROM  (
    SELECT 1 AS a, 1 AS b
    UNION ALL
    SELECT 2 AS a, 2 AS b
    UNION ALL
    SELECT 3 AS a, 3 AS b
  ) AS pair
  WHERE pair.a = data.a
    AND pair.b = data.b
);

数据IN对;如果对(a,b)是唯一的

SELECT     data.*
FROM       data
INNER JOIN (
  SELECT 1 AS a, 1 AS b
  UNION ALL
  SELECT 2 AS a, 2 AS b
  UNION ALL
  SELECT 3 AS a, 3 AS b
) AS pair
 ON  pair.a = data.a
AND  pair.b = data.b;

数据不是成对的;如果对(a,b)是唯一的

SELECT    data.*
FROM      data
LEFT JOIN (
  SELECT 1 AS a, 1 AS b
  UNION ALL
  SELECT 2 AS a, 2 AS b
  UNION ALL
  SELECT 3 AS a, 3 AS b
 ) AS pair
   ON pair.a = data.a
  AND pair.b = data.b
WHERE pair.a IS NULL
   OR pair.b IS NULL;

答案 1 :(得分:8)

这是一个易于使用的解决方案,但它可能无法在大型数据集上运行良好,因为它无法使用任何索引。

SELECT * FROM table
WHERE col1 || '-' || col2 in (
  'col1_val1-col2_val1',
  'col1_val2-col2_val2',
  'col1_val3-col2_val3'
)

Try it in sqlfiddle

享受!

答案 2 :(得分:1)

在sqlite中,尝试添加VALUES关键字:

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')
  )

基本上在sqLite中执行查询:

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

与以下相同:

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

或组合:

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

所以您甚至可以这样写:

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

这是一个简单的子查询,适用于所有/大多数数据库。