Sqlite3基于字母排序的伪索引列

问题描述 投票:0回答:1

在Sqlite3中,如何根据同一个表中另一列的字母顺序创建具有连续行号的伪索引列?

到目前为止,我一直在努力解决非常复杂的 SQL 查询来解决 python Web 应用程序中的简单问题。

我只想迭代记录(下一个前一个场景),而不弄乱索引并处理非顺序记录号。

简单地说,我有一个带有“title”列和“record_id”列的表。 (共 40 列)

这是一个只有大约 250 条记录的小表。标题很长,并且记录已被删除,其中缺少 record_id 编号。我大约每月只添加或删除一次记录(使用 SQLite 的数据库浏览器),并且不插入记录,只是在末尾添加它们,自动递增 record_id。

我想为什么不根据标题列的字母顺序向表中添加一个“title_sort_order”(整数)列,然后在我很少添加或删除记录时重新编号?

我知道如何使用 f 字符串(在本例中为“上一个”)来做这种事情:

f"SELECT record_id, title FROM { table } 
INDEXED BY { titles_index } 
WHERE title < '{ current_title_text }' 
ORDER BY title DESC LIMIT 1;"

非常麻烦。

StackOverflow 上有许多针对“下一个-上一个”问题的复杂解决方案(例如我在哪里找到上述问题),但新专栏会简单得多。

表格已有一列:

title_sort(int)

我想到编写一个小Python脚本来读取表格,使用类似这样的伪代码:

table_data = SELECT rowid, title FROM { table } 
INDEXED BY { titles_index } 
ORDER BY title ASC;

order = 1

for each row in table_data

    UPDATE { table }

    SET row.title_sort = order

    order = order + 1

但是我在编写代码时遇到了困难。

如有任何帮助,我们将不胜感激。谢谢你。

编辑:如果你们不知道该怎么做,就直接说出来。如果你只是想开枪射击我,那你就没有增加价值。我已经充分解释了原因和原因,这已经回答了您提出的问题。也许您只是在真正阅读之前发表了评论。

python sqlite indexing
1个回答
0
投票

我是这样做的。作为一名 sqlite 的 n00b,我确信这些步骤效率极低,但它们确实有效。

我刚刚创建了一个烧瓶路线和一个测试页面。导航到路线会更新表格,页面会显示结果。

import sqlite3
from flask import render_template

@app.route("/sort")
def sort():
    index = "ix_title"

    # Get the rows in alphabetical order. 
    # Selecting "title" is used for diagnostics
    statement_1 = f"SELECT rowid, title FROM { table } INDEXED BY { index } ORDER BY title ASC"

    conn = sqlite3.connect(PRACTICE)
    cursor = conn.cursor()
    cursor.execute(statement_1)
    row_data = cursor.fetchall()
    conn.close()

    # Now use "row_data" (indexed by title) from above 
    # to cycle through the table a row at a time.
    # "row_data" type is a list of tuples.  

    order = 1
    for row in row_data:
        # inside the tuple, row[0] will be the rowid from the query above
        statement2 = f"UPDATE { table } SET title_sort = { order } WHERE rowid = { row[0] }"
        conn = sqlite3.connect(PRACTICE)
        cursor = conn.cursor()
        cursor.execute(statement_2)
        sort_data = cursor.fetchall()
        conn.commit()
        conn.close()
    
# to test whether it worked correctly, grab the updated rows and send to a page

    statement_3 = f"SELECT rowid, title_sort, title FROM records"
    conn = sqlite3.connect(PRACTICE)
    cursor = conn.cursor()
    cursor.execute(statement_3)
    sort_test = cursor.fetchall()
    conn.close()

    return render_template("/sort.html", 
        row_data=row_data, 
        sort_test=sort_test)
© www.soinside.com 2019 - 2024. All rights reserved.