今天在用python连接数据库做力扣题时发现这样一个错误
Traceback (most recent call last):
File "D:/PYTHON/test/力扣/力扣.py", line 864, in <module>
cursor.execute(sql)
File "D:\pythonData\lib\site-packages\MySQLdb\cursors.py", line 209, in execute
res = self._query(query)
File "D:\pythonData\lib\site-packages\MySQLdb\cursors.py", line 315, in _query
db.query(q)
File "D:\pythonData\lib\site-packages\MySQLdb\connections.py", line 231, in query
_mysql.connection.query(self, query)
MySQLdb._exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Rank from scores s order by score desc' at line 1")
我的代码是这样得
import MySQLdb
conn=MySQLdb.Connect(host='localhost',user='root',password='123456',db='delete')
cursor=conn.cursor()
sql='select score,(select count(distinct score) from scores where score>=s.score) as Rank from scores s order by score desc;'
# sql='select count(distinct score) as Rank from scores where score'
cursor.execute(sql)
res=cursor.fetchall()
print(res)
cursor.close()
conn.close()
按照正常思路,系统提示得这一句就是问题所在: ‘Rank from scores s order by score desc’,然而当我去掉‘,(select count(distinct score) from scores where score>=s.score) as Rank’这句时,程序会正常运行,那这样得话错的岂不是“Rank”?
当我单独把这句话单独拿出来运行时也会报错,也不知道是什么原因。之后我在网上找也没找到答案,后来抱着尝试得心里把‘as Rank’删除了,程序正常运行。
((4.0, 1), (4.0, 1), (3.85, 2), (3.65, 3), (3.65, 3), (3.5, 4))
Process finished with exit code 0
后来,我在Navicat上也试了试sql语句,也会报错,但不去命名则会正常运行
所以,应该是pycharm等编译器不能命名显示的原因