21

我有一个看起来像这样的查询:

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 中有效的等效查询?

4

3 回答 3

14

选择您喜欢的版本:

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);
....

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

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

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

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

数据不是成对的;如果 pair(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;

使用内联表

数据成对;如果 pair(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
);

数据成对;如果 pair(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;

数据不是成对的;如果 pair(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;
于 2012-06-23T17:04:47.667 回答
10

这是一个可行的简单解决方案,但它可能在大型数据集上表现不佳,因为它不能使用您的任何索引。

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

在 sqlfiddle 中试试

享受!

于 2014-11-19T15:07:01.433 回答
7

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

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

于 2019-05-15T10:56:13.117 回答