MySQL是一種關系型數(shù)據(jù)庫管理系統(tǒng),可以處理許多數(shù)據(jù)表。在處理這些數(shù)據(jù)表時,我們經(jīng)常需要查詢所涉及的最高和最低值。此時,我們可以使用MySQL多表查詢來實現(xiàn)這個目的。
下面是使用MySQL多表查詢找到學生最高和最低成績的步驟:
1. 創(chuàng)建相關的數(shù)據(jù)表并插入數(shù)據(jù) CREATE TABLE students ( id INT NOT NULL AUTO_INCREMENT, name VARCHAR(50) NOT NULL, PRIMARY KEY (id) ); CREATE TABLE subjects ( id INT NOT NULL AUTO_INCREMENT, name VARCHAR(50) NOT NULL, PRIMARY KEY (id) ); CREATE TABLE scores ( stu_id INT NOT NULL, sub_id INT NOT NULL, score INT NOT NULL DEFAULT 0, PRIMARY KEY (stu_id, sub_id), FOREIGN KEY (stu_id) REFERENCES students(id), FOREIGN KEY (sub_id) REFERENCES subjects(id) ); INSERT INTO students (name) VALUES ("小明"), ("小紅"), ("小王"); INSERT INTO subjects (name) VALUES ("語文"), ("數(shù)學"), ("英語"); INSERT INTO scores (stu_id, sub_id, score) VALUES (1, 1, 90), (1, 2, 95), (1, 3, 85), (2, 1, 88), (2, 2, 92), (2, 3, 90), (3, 1, 85), (3, 2, 80), (3, 3, 87); 2. 查詢學生最高成績 SELECT students.name, MAX(scores.score) AS highest_score FROM students JOIN scores ON students.id = scores.stu_id GROUP BY students.id; 3. 查詢學生最低成績 SELECT students.name, MIN(scores.score) AS lowest_score FROM students JOIN scores ON students.id = scores.stu_id GROUP BY students.id;
通過以上步驟,我們可以方便地查詢到每個學生的最高和最低成績。這對于學生管理和教育管理都有很大的幫助。