tags:

views:

47

answers:

6

I have Table Students with columns Student ID and Student Name. I also have Table Events with columns ID, Student ID and Event.

Now, i want to write a query that will return only rows from Students Table that has its Student ID present in Events Table.

I am running MySql 5+.

A: 

You can write WHERE StudentId IN SELECT StudentId FROM Events. (Or at least you can in SQL Server)

SLaks
A: 
SELECT DISTINCT s.* FROM Students s INNER JOIN Events e ON e.StudentId = s.id;
soulmerge
This may return the same records multiple times
artemb
+3  A: 

Simple, inner join:

SELECT DISTINCT(Students.Id, Students.StudentName)
FROM Students
JOIN Events on Students.StudentId = Events.StudentId
ORDER BY Students.StudentName
Paul Sasik
Why the distinct on name? If two students have the same name 'John Smith', does this mean they are also the same person?
Mark Byers
@Mark: Good eyes. The distinct needs to include the ID.
Paul Sasik
When i used the join it worked on my local mysql but when i uploaded the code to my web hosting, it generated an exception about too many joins coz i was already using two joins before adding a third one. but SQLMenace method worked on both local and hosting mysql.thx very much
IndexController
I guess MySQL has a limit of 61 joins. Three is way too few to throw such exception
artemb
A: 
select students.ID, students.name 
from students join events on students.id = events.studentID 
group by students.ID, students.name
artemb
A: 
SELECT * FROM Students
WHERE StudentID IN (SELECT StudentID 
                    FROM Events 
                    WHERE Events.StudentID = Students.StudentID) 
Alex LE
This can be very slow
artemb
+1  A: 

besides JOIN and IN you can also use EXISTS

SELECT * FROM Students s
WHERE EXISTS  (SELECT * 
                    FROM Events e
                    WHERE e.StudentID = s.StudentID)
SQLMenace
Join is much faster
artemb
ON SQl Server a join and exists will result in the same exact execution plan for this case
SQLMenace
@SQLMenace: He's not using SQL Server. The question is tagged MySQL.
Mark Byers