Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

การใช้ฟังก์ชัน MIN() และ MAX() ใน MySQL ด้วย Python


ฟังก์ชัน MIN() และ MAX() ใช้สำหรับดำเนินการคำนวณบนคอลัมน์ของตาราง

  • MIN(): คืนค่าที่น้อยที่สุดจากคอลัมน์ที่เลือก
  • MAX(): คืนค่าที่มากที่สุดจากคอลัมน์ที่เลือก

ไวยากรณ์

MIN()

SELECT MIN(column_name) FROM table_name

MAX()

SELECT MAX(column_name) FROM table_name

ขั้นตอนหาค่าต่ำสุดและสูงสุดจากคอลัมน์ในตารางด้วย MySQL ใน Python

  • นำเข้า MySQL Connector

  • สร้างการเชื่อมต่อด้วย connect()

  • สร้างออบเจ็กต์ cursor ด้วย cursor()

  • สร้างคำสั่ง SQL ที่เหมาะสม

  • รันคำสั่งด้วย execute()

  • ปิดการเชื่อมต่อ

ตาราง Students มีชื่อและคะแนน ต้องการหาคะแนนต่ำสุดและสูงสุด

+----------+-----------+
| 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