我的表学生有列学生ID和学生姓名。我还有表事件,列ID,学生ID和事件。
现在,我想编写一个查询,该查询只返回学生表中具有学生ID的事件表中的行。
我正在运行MySql 5 +。
答案 0 :(得分:3)
简单的内部联接:
SELECT DISTINCT(Students.Id, Students.StudentName)
FROM Students
JOIN Events on Students.StudentId = Events.StudentId
ORDER BY Students.StudentName
答案 1 :(得分:1)
SELECT * FROM Students
WHERE StudentID IN (SELECT StudentID
FROM Events
WHERE Events.StudentID = Students.StudentID)
答案 2 :(得分:1)
除了JOIN和IN之外,你还可以使用EXISTS
SELECT * FROM Students s
WHERE EXISTS (SELECT *
FROM Events e
WHERE e.StudentID = s.StudentID)
答案 3 :(得分:0)
你可以写WHERE StudentId IN SELECT StudentId FROM Events
。 (或至少你可以在SQL Server中)
答案 4 :(得分:0)
SELECT DISTINCT s.* FROM Students s INNER JOIN Events e ON e.StudentId = s.id;
答案 5 :(得分:0)
select students.ID, students.name
from students join events on students.id = events.studentID
group by students.ID, students.name