CREATE TABLE `students` (
`id` int NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`age` int NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
CREATE TABLE `scores` (
`student_id` int NOT NULL,
`subject` varchar(255) NOT NULL,
`score` int NOT NULL,
PRIMARY KEY (`student_id`, `subject`),
KEY `student_id` (`student_id`),
CONSTRAINT `scores_ibfk_1` FOREIGN KEY (`student_id`) REFERENCES `students` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
题解:
SELECT s.age
FROM students s
JOIN (
SELECT student_id, AVG(score) AS avg_score
FROM scores
GROUP BY student_id
) sc ON s.id = sc.student_id
GROUP BY s.age
HAVING COUNT(s.id) > 2
AND AVG(sc.avg_score) > 60;