SQLite查询会在代码中引发语法错误,但将其复制到sqlite数据库浏览器后可以正常工作

时间:2019-09-19 16:14:26

标签: python sql sqlite

解决方案:我安装了一个过时的sqlite版本,该版本不支持RANK()。我通过安装Python3.7.4来解决了这个问题

当用户根据两列的总和以降序排序时,我试图找到他们的位置。我在SQLite DB浏览器中测试了此查询,并返回了正确的结果,但是当我将其复制到Python脚本中时,它在“(”

之一处引发了语法错误。

我已经尝试运行代码并在执行查询之前将其停止,以便可以将查询逐字复制到db浏览器中。当我这样做时,它可以完美运行,但是当我在脚本中执行查询时,它会失败

这是字符串连接返回的纯文本查询:

SELECT top_rank FROM (
    SELECT username, RANK() OVER(ORDER BY summed DESC) AS 'top_rank' 
    FROM (
        SELECT SUM(positive_qc) - SUM(negative_qc) AS 'summed', username 
        FROM sub_activity 
        WHERE sub_name IN('cryptocurrency', 'cryptomarkets', 'cryptotechnology', 'blockchain') 
    GROUP BY username)
) WHERE username = 'someuser'

这是我用来获取该查询的代码:

select_str = "SELECT top_rank FROM(" + \
                    "SELECT " + self.KEY2_USERNAME + ", RANK() OVER(ORDER BY summed DESC) AS 'top_rank' " \
                    "FROM(" \
                        "SELECT SUM(" + self.KEY2_POSITIVE_QC + ") - SUM(" + self.KEY2_NEGATIVE_QC + ") " \
                        "AS 'summed', " + self.KEY2_USERNAME + " " \
                        "FROM " + self.TABLE_SUB_ACTIVITY + " " \
                        "WHERE " + self.KEY2_SUB_NAME + " IN('" + "', '".join(sub_list) + "') " \
                    "GROUP BY " + self.KEY2_USERNAME + ")" \
             ") WHERE " + self.KEY2_USERNAME + " = ?"

在脚本中执行该错误的确切原因是

sqlite3.OperationalError: near "(": syntax error

更新:我将错误的范围缩小到查询的RANK()OVER(ORDER BY求和DESC)部分

1 个答案:

答案 0 :(得分:0)

尝试一下...我给每个子查询都加了别名。 uiuo

SELECT top_rank FROM (
    SELECT username, RANK() OVER(ORDER BY summed DESC) AS 'top_rank' 
    FROM (
        SELECT SUM(positive_qc) - SUM(negative_qc) AS 'summed', username 
        FROM sub_activity 
        WHERE sub_name IN ('cryptocurrency', 'cryptomarkets', 'cryptotechnology', 'blockchain') 
    GROUP BY username) ui
) uo WHERE username = 'someuser'