问题:
在这个例子中,我们有来自学校的5名学生的成绩1.我们想知道哪个学生的成绩最低。
我们期待获得4号学生,但SQL返回学生1
有人能帮助我吗? 提前致谢
表1:
CREATE TABLE `table1` (
`school_id` int(11) unsigned NOT NULL,
`student_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`grade` int(11) unsigned NOT NULL,
PRIMARY KEY (`student_id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
数据:
INSERT INTO `table1` (`school_id`, `student_id`, `grade`)
VALUES
(1, 1, 20),
(1, 2, 15),
(1, 3, 18),
(1, 4, 12),
(1, 5, 15);
SQL查询:
SELECT t1.`school_id`, t1.`student_id`, MIN(t1.grade)
FROM table1 as t1
WHERE t1.`school_id`=1
GROUP BY t1.`school_id`;
PRINTSCREEN:
答案 0 :(得分:2)
SELECT * FROM table1 ORDER BY grade LIMIT 1
如果你想要每所学校表现最差的学生,那就是......
SELECT x.*
FROM table1 x
JOIN
( SELECT school_id
, MIN(grade) grade
FROM table1
GROUP
BY school_id
) y
ON y.school_id = x.school_id
AND y.grade = x.grade;
答案 1 :(得分:0)
有了@ tadman的提示,我们提出了一个解决方案:
如果你遇到同样的问题,你可以找到它。
我们不明白为什么必须使用限制。如果我们取出限制行,我们会得到错误的结果
SELECT t2.`school_id`, t2.`student_id`, t2.grade
FROM
(
SELECT t1.`school_id`, t1.`student_id`, t1.grade
FROM table1 as t1
WHERE t1.`school_id`=1
ORDER BY t1.`grade` ASC
limit 4294967295
)
as t2
GROUP BY t2.`school_id`;
答案 2 :(得分:0)
除非对您的问题有更多要求,否则我猜您只会:
select t1.school_id, t1.student_id, t1.grade
from table1 as t1,
(select school_id, min(grade) as grade from table1 group by school_id) as t2
where t1.school_id=t2.school_id
and t1.grade=t2.grade;