Phil Howell
Phil Howell

Reputation: 79

Second query within a query using results of first query

The following select statement returns a list of students:

SELECT * FROM students2014 ORDER BY LastName

However, for each row I need to return data from another table (notes2014) to allow me to display the latest note for each student. The select statement would be as follows:

SELECT Note FROM notes2014 WHERE NoteStudent='$Student'

$Student indicates the ID for each student in the students2014 database. However this result only appears after the initial statement is queried.

So my question is, how can I run the second query within the first?

Upvotes: 0

Views: 109

Answers (3)

halfer
halfer

Reputation: 20487

Posted on behalf of the OP:

I've worked it out! Thank you for you help. I used left join in the end:

SELECT * FROM students2014
    LEFT JOIN notes2014 ON students2014.Student = notes2014.NoteStudent
    WHERE students2014.Consultant='$Consultant'
    ORDER BY students2014.LastName

Upvotes: 1

Sashi Kant
Sashi Kant

Reputation: 13465

Try this::

Select 
Student, 
Note 
from 
students2014 s
INNER JOIN notes2014 n on Student = n.NoteStudent
ORDER BY lastName

Upvotes: 0

roeb
roeb

Reputation: 497

you should query the data like this:

select students2014.*, notes2014.note from students2014, notes2014 where students2014.id = notes2014.NoteStudent

Upvotes: 0

Related Questions