Python中用MySQL解释MIN()和MAX()的用法?
该MIN()和MAX()功能用于在表列执行算术运算。
顾名思义,该MIN()函数用于从所选列中选择并返回最小的值。
MAX()另一方面,该函数从所选列中选择并返回最高值。
语法
MIN()
SELECT MIN(column_name) FROM table_name
MAX()
SELECT MAX(column_name) FROM table_name
在python中使用MySQL从表中的列中查找最小值和最大值的步骤
导入MySQL连接器
使用连接器建立连接connect()
使用cursor()方法创建游标对象
使用适当的mysql语句创建查询
使用execute()方法执行SQL查询
关闭连接
让我们有一个名为“Students”的表格,其中包含学生的姓名和分数。我们需要找出学生的最低分和最高分。我们可以在这个场景中使用MIN()和MAX()函数。MIN()在Marks列上操作的函数会给我们最低分,MAX()函数将返回最高分。
学生
+----------+-----------+ | name | marks | +----------+-----------+ | Rohit | 62 | | Rahul | 75 | | Inder | 99 | | Khushi | 49 | | Karan | 92 | +----------+-----------+
我们需要从上表中找出最低和最高分。
示例
import mysql.connector db=mysql.connector.connect(host="your host", user="your username", password="your password",database="database_name") cursor=db.cursor() query1="SELECT MIN(marks) FROM Students " cursor.execute(query1) lowest=cursor.fetchall() print(“Lowest marks :”,lowest) query2="SELECT MAX(marks) FROM Students " cursor.execute(query2) highest=cursor.fetchall() print(“Highest marks :”,highest) db.close()输出结果
Lowest marks : 49 Highest marks : 99