Subqueries As Calculated Columns : Sub query : Select Clause SQL / MySQL


SQL / MySQL » Select Clause » Sub query »

 

Subqueries As Calculated Columns



/*
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 Yin     |          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(50NOT 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,NameVALUES (1,'John Jones');
INSERT INTO Student (StudentID,NameVALUES (2,'Gary Burton');
INSERT INTO Student (StudentID,NameVALUES (3,'Emily Scarlett');

INSERT INTO StudentExam (StudentID,Mark,CommentsVALUES (1,55,'Java');
INSERT INTO StudentExam (StudentID,Mark,CommentsVALUES (1,73,'C#');
INSERT INTO StudentExam (StudentID,Mark,CommentsVALUES (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;

           
       



Leave a Comment / Note


 
Verification is used to prevent unwanted posts (spam). .

Follow Navioo On Twitter

SQL / MySQL

 Navioo Select Clause
» Sub query