Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL "chained" queries?

I have two tables.

I am a total newbie to SQL. Using mysql at the moment. I have the following setup for a school-related db:

Table A contains students records. Student's id, password,name, lastname and so on.

Table B contains class attendancy records. Each record goes like this: date, student id, grade

I need to gather all the student info of students that attended classes in a certain date range.

Now, the stupid way would be

  1. first I SELECT all classes from Table B with DATE IN BETWEEN the range

  2. then for each class, I get the student id and SELECT * FROM students WHERE id = student id

What I can't wrap my mind around is the smart way. How to do this in one query only. I am failing at understanding the concepts of JOIN, UNION and so on...

my best guess so far is

SELECT students.id, students.name, students.lastname 
FROM students, classes
WHERE classes.date BETWEEN 20140101 AND 20150101 
AND 
classes.studentid = students.id

but is this the appropriate way for this case?

like image 555
adam_b Avatar asked May 24 '26 03:05

adam_b


1 Answers

Dont add the join statement in the where clause. Do it like this:

SELECT s.id, s.name, s.lastname,c.date,c.grade 
FROM classes c
inner join students s
on c.studentid=s.id
WHERE c.date BETWEEN '01/01/2014' AND '01/01/2015'
like image 147
TheProvost Avatar answered May 25 '26 16:05

TheProvost



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!