SQLITE3如何快速高效地查询这个?

2024-10-03 02:36:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我想比较一个局部变量

currentTime = time.time()

在authord列下,查看哪个值更大。然后,我将继续将“提醒”列更新为True。我的桌子被称为。你知道吗

这就是数据库的外观:http://prntscr.com/gb9ay1

最好的办法是什么?我相信我可以专门获取FutureTime并将其存储为变量,然后将其与currentTime进行比较。但是,有没有更好的方法可以更快更有效地使用查询?你知道吗

谢谢


Tags: 方法com数据库truehttptime外观桌子
2条回答

在sqlite3中,您可以在query中使用Case语句来检查当前时间是否小于或大于AuthorID。为此,您在sqlite3中的查询如下:

select case AuthorID<Futuretime then 1 else 0 end from table;

这应该在列中为您提供10,而不必花时间使用python。你知道吗

我认为,最好的做法是使用一条SQL语句来更新记录。你知道吗

因为SQLite has no boolean value,所以需要设置值1(而不是True)。你知道吗

例如,语句可以是:

import time

st = "UPDATE reminderFormat SET Reminded = 1 " \
     "WHERE FutureTime <= {currentTime}".format(currentTime=time.time())

编辑:演示

下面是一个演示:

import time
import sqlite3

records = [
    (20183740995, 1503330725.0, "testtt", 0),
    (20183740995, 1503330732.0, "testtt", 0),
    (20183740995, 1503331334.0, "testtt", 0),
    (20183740995, 1509999999.0, "testtt", 0),
    ]

con = sqlite3.connect(":memory:")

# Create the table
con.execute("create table reminderFormat(AuthorID, FutureTime, Message, Reminded)")

# Fill the table
con.executemany("INSERT INTO reminderFormat(AuthorID, FutureTime, Message, Reminded) VALUES (?, ?, ?, ?)", records)

curr_time = time.time()
con.execute("UPDATE reminderFormat SET Reminded = 1 WHERE FutureTime <= ?", (curr_time,))

# Print the table contents
for row in con.execute("SELECT AuthorID, FutureTime, Reminded FROM reminderFormat"):
    print(row)

你会得到:

(20183740995, 1503330725.0, 1)
(20183740995, 1503330732.0, 1)
(20183740995, 1503331334.0, 1)
(20183740995, 1509999999.0, 0)

相关问题 更多 >