【问题标题】:Sorting Problem with SQLite 3 on Discord.pyDiscord.py 上 SQLite 3 的排序问题
【发布时间】:2020-11-26 13:32:03
【问题描述】:

所以我尝试制作一个Leveling系统,它可以工作,但是排行榜不能正常工作,它随机排序SQLite内容虽然我已经放了ORDER BY lvl also我尝试了ORDER BY txp(txp是总xp),这是我写的代码

    @commands.command()
    async def top10(self, ctx):
        db = sqlite3.connect('main.db')
        cursor = db.cursor()
        cursor.execute(f"SELECT user_id, lvl, txp from levels WHERE guild_id = {ctx.guild.id} ORDER BY txp DESC LIMIT 5 ")
        result = cursor.fetchall()
        embed = discord.Embed(title="Leaderboards", colour=discord.Colour(0x6790a7))
        for i, x in enumerate(result, 1):
            embed.add_field(name=f"#{i}", value=f"<@{str(x[0])}> on Level {str(x[1])} with {str(x[2])} Total XP", inline=False)
        await ctx.send(embed=embed)
        print(result)
        cursor.close()
        db.close()

这是结果

[('560578285747306538', '5', '830'), ('441240050861211648', '8', '548'), ('321191503487827970', '4', '548'), ('457159518254792714', '0', '4'), ('448779471810461706', '1', '36')]``` when I print the db

这是排行榜的样子 Leaderboards looks like

【问题讨论】:

    标签: python sqlite discord discord.py


    【解决方案1】:

    我猜txp的数据类型是TEXT所以结果是按字母顺序排序的。
    您必须将其转换为整数:

    cursor.execute(f"SELECT user_id, lvl, txp from levels WHERE guild_id = {ctx.guild.id} ORDER BY txp + 0 DESC LIMIT 5")
    

    txp + 0txp 隐式转换为整数。

    【讨论】:

    • 如果我将列类型更改为整数而不是转换它会怎样?
    • 是的,它会起作用的。但是如果要保留现有数据,在 SQLite 中就没有那么简单了。 SQLite 不支持更改列的数据类型。如果您不关心现有数据,请删除该表并重新创建它。
    猜你喜欢
    • 1970-01-01
    • 2011-12-10
    • 1970-01-01
    • 1970-01-01
    • 2014-11-29
    • 2012-10-30
    • 1970-01-01
    • 2015-04-01
    • 1970-01-01
    相关资源
    最近更新 更多