我有一个存储主题结果的简单表格。所以一个用户可能做了很少的主题,他们可能有不同的标记。我想做一个商店程序来检索给定学生的最小和最大主题细节
DELIMITER $$
CREATE DEFINER=`root`@`localhost`
PROCEDURE `Search_Min_Marks_For_Student`(IN Student_code SMALLINT)
BEGIN
SELECT Subject_Subject_code AS `Minimum Scored Subject`,
Subject_title AS `Subject Title`,
Min(Total_mk) AS Marks
FROM result,subject
WHERE result.Student_Student_code = Student_code AND
Subject_Subject_code=Subject_code;
END
我写了一个最低分,它工作正常。但有没有办法可以将最大结果添加到同一个查询?
这是
result
DROP TABLE IF EXISTS result
;
/ *!40101 SET @saved_cs_client = @@ character_set_client /;
/ !40101 SET character_set_client = utf8 * /;
CREATE TABLE result
(
Result_code
smallint(6)NOT NULL AUTO_INCREMENT,
Student_Student_code
smallint(6)NOT NULL,
Subject_Subject_code
smallint(6)NOT NULL,
Practical_mk
smallint(6)NOT NULL,
Assignment_mk
smallint(6)NOT NULL,
Exam_mk
smallint(6)NOT NULL,
Total_mk
smallint(6)NOT NULL,
Grade
varchar(20)NOT NULL,
PRIMARY KEY(Result_code
),
KEY fk_Result_Subject1_idx
(Subject_Subject_code
),
KEY fk_Result_Student1_idx
(Student_Student_code
),
CONSTRAINT fk_Result_Student1
FOREIGN KEY(Student_Student_code
)引用student
(Student_code
)在更新时不执行任何操作,
CONSTRAINT fk_Result_Subject1
FOREIGN KEY(Subject_Subject_code
)引用subject
(Subject_code
)ON更新没有操作更新无操作
)ENGINE = InnoDB AUTO_INCREMENT = 26 DEFAULT CHARSET = utf8;
/ *!40101 SET character_set_client = @saved_cs_client * /;
和主题
-
subject
DROP TABLE IF EXISTS subject
;
/ *!40101 SET @saved_cs_client = @@ character_set_client /;
/ !40101 SET character_set_client = utf8 * /;
CREATE TABLE subject
(
Subject_code
smallint(6)NOT NULL AUTO_INCREMENT,
Subject_title
varchar(50)NOT NULL,
Num_of_credits
smallint(6)NOT NULL,
Description
varchar(100)DEFAULT NULL,
Course_Course_code
smallint(6)NOT NULL,
Department_Dep_code
smallint(6)NOT NULL,
PRIMARY KEY(Subject_code
),
KEY fk_Subject_Course1_idx
(Course_Course_code
),
KEY fk_Subject_Department1_idx
(Department_Dep_code
),
CONSTRAINT fk_Subject_Course1
FOREIGN KEY(Course_Course_code
)引用course
(Course_code
)在更新时不执行任何操作,
CONSTRAINT fk_Subject_Department1
FOREIGN KEY(Department_Dep_code
)引用department
(Dep_code
)ON更新没有操作更新无操作
)ENGINE = InnoDB AUTO_INCREMENT = 8004 DEFAULT CHARSET = utf8;
/ *!40101 SET character_set_client = @saved_cs_client * /;
答案 0 :(得分:0)
你可以使用(有点冗长的)连接以及相应的代码和标题来获得两者。此查询将最佳和最差主题作为两个单独的行返回;
SELECT DISTINCT s.Subject_Subject_code, s.Subject_title, r1.Total_mk
FROM result r1
LEFT JOIN result r2
ON r1.Total_mk > r2.Total_mk
AND r1.Student_Student_code = r2.Student_Student_code
LEFT JOIN result r3
ON r1.Total_mk < r3.Total_mk
AND r1.Student_Student_code = r3.Student_Student_code
JOIN Subject s
ON r1.Subject_code=s.Subject_Subject_code
WHERE (r2.Total_mk IS NULL OR r3.Total_mk IS NULL)
AND r1.Student_Student_code = 1;
它的作用基本上是选择没有较低分数的行(r2连接)或者学生没有更好的分数(r3连接),并加入主题以获取要显示的数据。