让我们说我们有这个数据集:
import sqlite3
db = sqlite3.connect(':memory:')
c = db.cursor()
c.execute('CREATE TABLE mytable (id integer, description text)')
c.execute('INSERT INTO mytable VALUES (2, "abc")')
c.execute('INSERT INTO mytable VALUES (5, "def")')
c.execute('INSERT INTO mytable VALUES (18, "geh")')
c.execute('INSERT INTO mytable VALUES (19, "ijk")')
c.execute('INSERT INTO mytable VALUES (27, "lmn")')
如何找到ID最远为3的行/对行?即它应返回行(2,5)和(18,19),也可能(5,2),(19,18)(但不需要最后两个)。
我试过了:
c.execute('SELECT id as id1 FROM mytable, SELECT id as id2 FROM mytable WHERE abs(id1 - id2) <= 3')
但它似乎不起作用:
sqlite3.OperationalError:靠近“SELECT”:语法错误
答案 0 :(得分:2)
试试这个:
SELECT mt1.*, mt2.* FROM mytable mt1, mytable mt2 WHERE abs(mt1.id - mt2.id) <= 3 and mt1.id<mt2.id
输出:
[(2, u'abc', 5, u'def'), (18, u'geh', 19, u'ijk')]
条件mt1.id<mt2.id
用于删除重复项。
答案 1 :(得分:1)
SELECT t1.id, t2.id
FROM mytable t1
CROSS JOIN mytable t2
WHERE t1.id != t2.id AND abs(t1.id - t2.id) <= 3
输出:
[(2, 5), (5, 2), (18, 19), (19, 18)]