Subqueries As Calculated Columns: Simple Subqueries
/*
mysql> SELECT StudentID, Name,
-> (SELECT COUNT(*) FROM StudentExam
-> WHERE StudentExam.StudentID = Student.StudentID)
-> AS ExamsTaken
-> FROM Student
-> ORDER BY ExamsTaken DESC;
+-----------+-------------+------------+
| StudentID | Name | ExamsTaken |
+-----------+-------------+------------+
| 1 | Joe Wang | 2 |
| 2 | Cory But | 1 |
| 3 | JJ Harvests | 0 |
+-----------+-------------+------------+
3 rows in set (0.00 sec)
*/
/* Create Student and StudentExam TABLE */
Drop TABLE Student;
Drop TABLE StudentExam;
CREATE TABLE Student (
StudentID INT NOT NULL PRIMARY KEY,
Name VARCHAR(50) NOT NULL
)TYPE = InnoDB;
CREATE TABLE StudentExam (
StudentID INT NOT NULL,
Mark INT,
Comments VARCHAR(255),
CONSTRAINT FK_Student FOREIGN KEY (StudentID)
REFERENCES Student(StudentID)
)TYPE = InnoDB;
/* Insert Data*/
INSERT INTO Student (StudentID,Name) VALUES (1,'John Jones');
INSERT INTO Student (StudentID,Name) VALUES (2,'Gary Burton');
INSERT INTO Student (StudentID,Name) VALUES (3,'Emily Scarlett');
INSERT INTO StudentExam (StudentID,Mark,Comments) VALUES (1,55,'Java');
INSERT INTO StudentExam (StudentID,Mark,Comments) VALUES (1,73,'C#');
INSERT INTO StudentExam (StudentID,Mark,Comments) VALUES (2,44,'JavaScript');
/* Real command */
SELECT StudentID, Name,
(SELECT COUNT(*) FROM StudentExam
WHERE StudentExam.StudentID = Student.StudentID)
AS ExamsTaken
FROM Student
ORDER BY ExamsTaken DESC;
Related examples in the same category