【问题标题】:Bug in SQLite self-join on id?id 上的 SQLite 自连接中的错误?
【发布时间】:2010-09-23 04:10:27
【问题描述】:

我正在尝试根据它们的 id 生成成对的行组合。 SQLite 版本是 3.5.9。表格内容如下:

id|name|val  
1|A|20
2|B|21
3|C|22

表架构为:

CREATE TABLE mytable (
    id INTEGER NOT NULL, 
    name VARCHAR, 
    val INTEGER, 
    PRIMARY KEY (id)
);

然后是 ids 上的自加入:

sqlite> select t1.id, t2.id from mytable as t1, mytable as t2 where t2.id > t1.id;
id|id
2|2
2|3
3|3

这显然不是我想要的。现在,改变 t2 和 t1 的顺序会产生正确的结果:

sqlite> select t1.id, t2.id from mytable as t2, mytable as t1 where t2.id > t1.id;
id|id
1|2
1|3
2|3

现在,对于另一个实验,我尝试在除行 ID 之外的数字列上进行组合。另一方面,这在两种情况下都给出了正确的结果。

我希望有人可以深入了解这里发生的事情。据我了解,它要么是 SQLite 中的错误,要么是我不知道的 SQL 的某些微妙方面。

谢谢,

【问题讨论】:

    标签: sql sqlite join


    【解决方案1】:

    似乎是 SQLite 中的一个错误 - 正如您所怀疑的那样,您发布的第一个结果是错误的。我已经在我的工作站上的 PG8.3 和 sqlite3.6.4 上对其进行了测试,无法重现。在所有情况下都得到了正确的结果。可能与您的 sqlite 版本相关联;尝试升级。

    【讨论】:

    • 通过python确认sqlite 3.3.14中第一个查询的正确结果。
    【解决方案2】:
    SQLite version 3.6.2
    Enter ".help" for instructions
    Enter SQL statements terminated with a ";"
    sqlite> create table mytable (
       ...> id integer not null,
       ...> name varchar,
       ...> val integer,
       ...> primary key (id)
       ...> );
    sqlite> insert into mytable values(null,'A',20);
    sqlite> insert into mytable values(null,'B',21);
    sqlite> insert into mytable values(null,'C',22);
    sqlite> select t1.id, t2.id from mytable as t1, mytable as t2 where t2.id > t1.id;
    1|2
    1|3
    2|3
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多