【问题标题】:Unexpected behaviour with sqlitesqlite 的意外行为
【发布时间】:2020-10-09 11:22:54
【问题描述】:

我有 2 张桌子,一张是 {number,letter} 另一个是 {number,number}

我想选择 {number,letter},其中在 {number,number} 中的任何位置都提到了数字

看起来您的帖子主要是代码;请添加更多细节。因此,在遇到一些麻烦以通过下面的代码非常容易地重现该问题之后,我会胡扯一会儿。

/*
    Unexpected behaviour with sqlite.

    Save this as problem.sql and do sqlite3 < problem.sql
    to demonstrate the effect.

    I have 2 tables, 1 is {number,letter} the other {number,number}

    I want to select {number,letter} where number is mentioned 
    anywhere in {number,number}

    So my query is 
    SELECT ALL num,letter
    FROM numberLetter
    WHERE num IN (
    (
    SELECT n1 FROM pairs
    UNION
    SELECT n2 FROM pairs;
    )
    );

    I've actually wrapped this up with some views in the sql below,
    results are the same whatever way you do it.

    I think I'm making a stupid mistake or have a conceptual problem?

    results:
    $ sqlite3 < problem.sql
    this is pairList
    n1
    2
    3
    4
    5
    7
    8

    this is selectedNumberLetter which I expect to have 6 rows...
    num|letter
    2|b
*/
PRAGMA foreign_keys=OFF;
BEGIN TRANSACTION;
CREATE TABLE pairs(
  "n1" TEXT,
  "n2" TEXT
);
INSERT INTO pairs VALUES('2','3');
INSERT INTO pairs VALUES('5','4');
INSERT INTO pairs VALUES('8','7');
CREATE TABLE numberLetter(
  "num" TEXT,
  "letter" TEXT
);
INSERT INTO numberLetter VALUES('1','a');
INSERT INTO numberLetter VALUES('2','b');
INSERT INTO numberLetter VALUES('3','c');
INSERT INTO numberLetter VALUES('4','d');
INSERT INTO numberLetter VALUES('5','e');
INSERT INTO numberLetter VALUES('6','f');
INSERT INTO numberLetter VALUES('7','g');
INSERT INTO numberLetter VALUES('8','h');
INSERT INTO numberLetter VALUES('9','i');
INSERT INTO numberLetter VALUES('10','j');

CREATE VIEW pairList AS 
SELECT n1 FROM pairs
UNION
SELECT n2 FROM pairs;

CREATE VIEW selectedNumberLetter AS 
SELECT ALL num,letter
FROM numberLetter
WHERE num IN (
(
    SELECT n1 FROM pairList
)
);
COMMIT;

SELECT 'this is pairList';
.header on
SELECT * FROM pairList;
.header off
SELECT '
this is selectedNumberLetter which I expect to have 6 rows...';
.header on
SELECT * FROM selectedNumberLetter;

【问题讨论】:

    标签: sqlite select subquery union


    【解决方案1】:

    问题出在这里:

    WHERE num IN ((SELECT n1 FROM pairList));
    

    您不能将SELECT 语句括在另一组括号中,因为如果这样做,SQLite 最终将只返回来自pairList 的一行而不是所有行。

    改为:

    CREATE VIEW selectedNumberLetter AS 
    SELECT num,letter
    FROM numberLetter
    WHERE num IN (SELECT n1 FROM pairList);
    

    但使用EXISTS 更容易解决这个要求:

    select n.* 
    from numberLetter n
    where exists (select 1 from pairs p where n.num in (p.n1, p.n2));
    

    请参阅demo

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-06
    • 2020-10-04
    • 2016-07-16
    • 2016-05-10
    • 2020-07-23
    • 2021-08-23
    相关资源
    最近更新 更多