如何在SQL中正确使用左连接

时间:2017-04-13 11:24:19

标签: mysql sql

我正在编写一个SQL select查询,该查询将检索在couse_name字段中包含单词“Development”的课程中注册的学生的所有名称。

我是新手,这是我的SQL代码:

select firstname, lastname
FROM students INNER JOIN registrations
ON students.student_id = registrations.student_id
and course_name  = registrations.course_name LIKE '%Development%';

我知道这是错的,我想知道如何正确使用左连接以检索有效数据。 我附上了一些表格截图。

学生表:

Students Table

课程表:

enter image description here

注册表:

enter image description here

3 个答案:

答案 0 :(得分:1)

我会使用IN子句和INNER JOIN,而不是左连接:

--privileged

子查询将返回select s.* from students s where student_id IN ( select student_id from registrations r inner join courses c on r.course_code = c.course_code where c.course_name like '%Development%' ) 包含单词student_id的所有registrations中的所有course_name。外部查询将返回Development的所有学生信息。

答案 1 :(得分:1)

使用此查询

select students .firstname, students.lastname
FROM students INNER JOIN registrations
ON students.student_id = registrations.student_id
inner join courses on courses.course_code=registrations.course_code
where course.course_name LIKE '%Development%';

答案 2 :(得分:1)

如果您想要一个查询,该查询将显示每个学生以及他是否注册了该课程,您可以使用find("C:\\", ["file1.abc", "file2.abc", "file3.abc", "file4.abc", "file5.abc"]) ,如下所示:

LEFT JOIN