>我正在尝试在队列中找到票证的位置号。查询在 sqlite3 失败,给出的错误非常奇特:sqlite3.OperationalError: near "(": syntax error
。我似乎不明白如何使用列引用。
我尝试分离成更多的子查询,查看了无数的聚合使用示例,窗口函数等。我没有发现的是皮尤fn.ROW_NUMBER
的例子。我在多个网站上检查了查询,他们会鹦鹉学舌地出现同样的错误。
由皮尤生成的查询:
SELECT ROW_NUMBER() OVER (ORDER BY "t1"."ordinal") AS ordinal_index
FROM "dbticket" AS t1
WHERE (((("t1"."called_at" IS ?) AND ("t1"."abandoned_at" IS ?)) AND ("t1"."removed_at" IS ?)) AND ("ticket_id" = ?))
参数:
[None, None, None, 'red-shibe'
负责这个地狱的代码:
from pathlib import Path
import os
THIS_FOLDER = Path(os.path.dirname(os.path.abspath(__file__)))
db_file = THIS_FOLDER / 'queue.db'
sqlite_db = SqliteDatabase(str(db_file), pragmas=[('journal_mode', 'wal')])
class DBTicket(BaseModel):
ordinal = PrimaryKeyAutoIncrementField()
ticket_id = TextField(unique=True)
queue_name = TextField()
initiated_at = DateTimeField(default=datetime.utcnow)
called_at = DateTimeField(null=True)
abandoned_at = DateTimeField(null=True)
removed_at = DateTimeField(null=True)
def __str__(self):
return f'{self.ordinal}:{self.ticket_id}'
in_queue_predicate = (DBTicket.called_at.is_null() &
DBTicket.abandoned_at.is_null() &
DBTicket.removed_at.is_null())
def ticket_place_number(ticket_id):
queue = DBTicket.select()
.where(in_queue_predicate)
place_number = queue.select(fn.ROW_NUMBER().over(order_by=[DBTicket.ordinal]).alias('ordinal_index'))
.where(queue.c.ticket_id == ticket_id)
.scalar()
return place_number
我没有看到任何直接的问题,除了您可能会检查您的 sqlite 版本。窗口函数是相对较新的添加,您需要 3.25.0 或更高版本。
import sqlite3
sqlite3.sqlite_version