MySQL是一款強(qiáng)大的關(guān)系型數(shù)據(jù)庫(kù)管理系統(tǒng),對(duì)于管理、存儲(chǔ)和處理大量數(shù)據(jù)十分有效。在我們的學(xué)習(xí)中,我們也需要使用MySQL來(lái)對(duì)每個(gè)同學(xué)的科目進(jìn)行總結(jié)和分析。
CREATE DATABASE `student_db` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci; USE `student_db`; CREATE TABLE `student` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(50) NOT NULL COMMENT '學(xué)生姓名', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE `subject` ( `id` int(11) NOT NULL AUTO_INCREMENT, `subject_name` varchar(50) NOT NULL COMMENT '科目名稱', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE `student_subject` ( `id` int(11) NOT NULL AUTO_INCREMENT, `student_id` int(11) NOT NULL COMMENT '學(xué)生ID', `subject_id` int(11) NOT NULL COMMENT '科目ID', `score` int(11) NOT NULL COMMENT '成績(jī)', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
上述代碼創(chuàng)建了三個(gè)表,分別為學(xué)生表(student)、科目表(subject)和學(xué)生科目表(student_subject)。其中,學(xué)生表和科目表用于存儲(chǔ)學(xué)生和科目的信息,而學(xué)生科目表則用于存儲(chǔ)每個(gè)同學(xué)每門科目的成績(jī)。
-- 插入學(xué)生信息 INSERT INTO `student`(`name`) VALUES ('張三'); INSERT INTO `student`(`name`) VALUES ('李四'); INSERT INTO `student`(`name`) VALUES ('王五'); -- 插入科目信息 INSERT INTO `subject`(`subject_name`) VALUES ('數(shù)學(xué)'); INSERT INTO `subject`(`subject_name`) VALUES ('語(yǔ)文'); INSERT INTO `subject`(`subject_name`) VALUES ('英語(yǔ)'); -- 插入學(xué)生科目信息 INSERT INTO `student_subject`(`student_id`, `subject_id`, `score`) VALUES (1, 1, 90); INSERT INTO `student_subject`(`student_id`, `subject_id`, `score`) VALUES (1, 2, 85); INSERT INTO `student_subject`(`student_id`, `subject_id`, `score`) VALUES (1, 3, 80); INSERT INTO `student_subject`(`student_id`, `subject_id`, `score`) VALUES (2, 1, 70); INSERT INTO `student_subject`(`student_id`, `subject_id`, `score`) VALUES (2, 2, 75); INSERT INTO `student_subject`(`student_id`, `subject_id`, `score`) VALUES (2, 3, 80); INSERT INTO `student_subject`(`student_id`, `subject_id`, `score`) VALUES (3, 1, 85); INSERT INTO `student_subject`(`student_id`, `subject_id`, `score`) VALUES (3, 2, 80); INSERT INTO `student_subject`(`student_id`, `subject_id`, `score`) VALUES (3, 3, 90);
在插入數(shù)據(jù)之后,我們就可以對(duì)每個(gè)同學(xué)的科目成績(jī)進(jìn)行總結(jié)和分析了。例如,我們可以使用以下SQL語(yǔ)句查詢每個(gè)同學(xué)的平均成績(jī):
SELECT s.name AS student_name, AVG(ss.score) AS average_score FROM student_subject ss JOIN student s ON ss.student_id = s.id GROUP BY s.name;
除了平均成績(jī)外,我們還可以使用MySQL進(jìn)行更多方面的數(shù)據(jù)分析和處理,只需結(jié)合實(shí)際情況進(jìn)行SQL語(yǔ)句的編寫即可。