开发者

Returning rows that has matching record in another table

开发者 https://www.devze.com 2022-12-18 10:01 出处:网络
I have Table Students with columns Student ID and Student Name. I also have Ta开发者_如何学编程ble Events with columns ID, Student ID and Event.

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;
0

精彩评论

暂无评论...
验证码 换一张
取 消