การดำเนินการทางคณิตศาสตร์ ได้แก่ การบวก ลบ คูณ หาร และ modulus ทำงานบนข้อมูลตัวเลขในตาราง
ไวยากรณ์
การบวก:
SELECT op1 + op2 FROM table_name
op1 และ op2 เป็นชื่อคอลัมน์หรือค่าตัวเลข หากเป็นค่าตัวเลข ไม่ต้องใช้ FROM clause
เปลี่ยน + เป็น -, *, %, / สำหรับการดำเนินการอื่นๆ
ขั้นตอนดำเนินการคำนวณในตารางด้วย MySQL ใน Python
นำเข้า MySQL Connector
สร้างการเชื่อมต่อด้วย
connect()สร้างออบเจ็กต์ cursor ด้วย
cursor()สร้างคำสั่ง SQL ที่เหมาะสม
รันคำสั่งด้วย
execute()ปิดการเชื่อมต่อ
สมมติว่ามีตาราง Sales:
+------------+---------+ | sale_price | tax | +------------+---------+ | 1000 | 200 | | 500 | 100 | | 50 | 50 | | 180 | 180 | +------------+---------+
ตัวอย่าง
คำนวณยอดรวม (amount) จาก sale_price + tax
import mysql.connector
db = mysql.connector.connect(
host="your_host",
user="your_username",
password="your_password",
database="database_name"
)
cursor = db.cursor()
query = "SELECT sale_price, tax, CONCAT(sale_price + tax) AS amount FROM Sales"
cursor.execute(query)
rows = cursor.fetchall()
for row in rows:
print(row)
db.close()ผลลัพธ์
('sale_price', 'tax', 'amount')
(1000, 200, 1200)
(500, 100, 600)
(50, 50, 100)
(180, 180, 360)สามารถนำไปประยุกต์กับการดำเนินการทางคณิตศาสตร์อื่นๆ ได้ตามต้องการ