Returning rows that has matching record in another table
I have Table Students with columns Student ID and Student Name. I also have Ta开发者_如何学编程ble 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+.
Simple, inner join:
SELECT DISTINCT(Students.Id, Students.StudentName)
FROM Students
JOIN Events on Students.StudentId = Events.StudentId
ORDER BY Students.StudentName
besides JOIN and IN you can also use EXISTS
SELECT * FROM Students s
WHERE EXISTS (SELECT *
FROM Events e
WHERE e.StudentID = s.StudentID)
SELECT * FROM Students
WHERE StudentID IN (SELECT StudentID
FROM Events
WHERE Events.StudentID = Students.StudentID)
You can write WHERE StudentId IN SELECT StudentId FROM Events
. (Or at least you can in SQL Server)
select students.ID, students.name
from students join events on students.id = events.studentID
group by students.ID, students.name
SELECT DISTINCT s.* FROM Students s INNER JOIN Events e ON e.StudentId = s.id;
精彩评论