Skip to content

Instantly share code, notes, and snippets.

@vbarinov
Created April 10, 2017 06:48
Show Gist options
  • Save vbarinov/c87489b4d06f89e62882bac66633bdd7 to your computer and use it in GitHub Desktop.
Save vbarinov/c87489b4d06f89e62882bac66633bdd7 to your computer and use it in GitHub Desktop.
Mutual student

Structure

CREATE TABLE teacher(
	id INT(10) PRIMARY KEY NOT NULL AUTO_INCREMENT,
	name VARCHAR(100) NOT NULL
);

CREATE TABLE student(
	id INT(10) PRIMARY KEY NOT NULL AUTO_INCREMENT,
	name VARCHAR(100) NOT NULL
);

CREATE TABLE teacher_student (
	teacher_id INT(10) NOT NULL, 
	student_id INT(10) NOT NULL
);

Teachers with more than 5 students

SELECT t.* FROM teacher t JOIN teacher_student ts ON ts.teacher_id = t.id
GROUP BY t.id HAVING COUNT(ts.student_id) > 5;

Two first teachers with maximum mutual students

SELECT t.name, ts2.teacher_id as mutual_id, COUNT(ts1.student_id) as mutual_count
FROM teacher_student ts1
  INNER JOIN
    teacher_student ts2 ON ts1.teacher_id != ts2.teacher_id AND ts1.student_id = ts2.student_id
  JOIN teacher t ON ts1.teacher_id = t.id
GROUP BY ts1.teacher_id, ts2.teacher_id ORDER BY mutual_count DESC LIMIT 2;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment