简体   繁体   English

MySQL & Python select 最后对应的行而不是第一行

[英]MySQL & Python select last corresponding row instead of first

I had a quick question.我有一个快速的问题。 I want to count how many times a user is logged into the system.我想统计一个用户登录系统的次数。 To achieve this i add a 1 to the third part of the result.为此,我在结果的第三部分加了 1。 The only thing is that every time the user logs in the code fetches the first corresponding row.唯一的问题是每次用户登录时,代码都会获取第一个对应的行。 Thus resulting in the fact that the login_num will always be 2, since the first corresponding row always contains a 1.因此导致 login_num 始终为 2,因为第一个对应行始终包含 1。

On Stackoverflow i searched for several solutions.在 Stackoverflow 上,我搜索了几种解决方案。 So i came up with the DESC at the end of the fetch syntax.所以我在提取语法的末尾想出了 DESC 。 However in every instance i tried this, i always end up getting an error in return.然而,在我尝试过的每一个实例中,我总是以返回错误告终。 Does anyone have an idea why this is the case?有谁知道为什么会这样?

Python code: Python 代码:

cursor.execute("Select rfid_uid, name, login_num FROM users rfid_uid="+str(id) + "ORDER BY id DESC")
result = cursor.fetchone()

if cursor.rowcount >= 1:
  print("Welkom " + result[1])
  print(result)
  result = (result[0], result[1], result[2] + 1)
  sql_insert = "INSERT INTO users (rfid_uid, name, login_num) VALUES (%s, %s, %s)"
  cursor.execute(sql_insert, (result))
  db.commit()

Seems your SQL statement refers to table 'users'.似乎您的 SQL 语句引用了表“用户”。 I suppose it does contain info about users in general (a row per user), not user logins.我想它确实包含有关一般用户的信息(每个用户一行),而不是用户登录信息。

If you have each individual user login event registered in some table, I would let the database do the counting.如果您在某个表中注册了每个单独的用户登录事件,我会让数据库进行计数。 Something like this:是这样的:

SELECT COUNT(*) FROM user_logins WHERE rfid_uid='user_id';

You should get one row, which has your answer as an integer.你应该得到一行,你的答案是 integer。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM