提问者:小点点

SQL JOIN 2表


我有两张这样的桌子

学生

|-----------------------|
| id  | name   | value  |
|-----------------------|
| F01 | Ruben  | 4      |
| F02 | Dani   | 2      |
| F03 | Mike   | 3      |
| F04 | John   | 4      |
|-----------------------|

导师

|-------------------------|
| id | code  | student_id |
|-------------------------|
| 1  | S2244 | F01        |
| 2  | S3251 | F02        |
| 3  | S2244 | F03        |
| 4  | S2244 | F04        |
|-------------------------|

注意,tutor.code(S2244和S3251)是来自另一个表的外键,tutor.student_id是来自student表的外键,如何使这两个表组合起来产生如下结果?

|-----------------------|
| id  | name   | value  |
|-----------------------|
| F01 | Ruben  | 4      |
| F03 | Mike   | 3      |
| F04 | John   | 4      |
|-----------------------|

结果与student表相同,但数据是基于存储在tutor表中的内容发布的,在tutor表中有代码“S3251”/“F02”,该代码在结果表中没有显示

这就像“WHERE”条件,但是WHERE“condition”在其他表中使用,我尝试过使用JOIN,但是我不能,或者可能我的表设计是错误的? 请帮助,这个代码是我做的,但没有得到一个好的结果

SELECT st.id, st.name, st.value FROM student st JOIN tutor tt ON tt.code = 'S2244'

共1个答案

匿名用户

您可以使用exists:

select s.*
from students s
where exists (
    select 1 from tutor t where t.student_id = s.student_id and t.code = 'S2244'
)

这比join更有意义,因为您不是从tutor表中执行select)。

您最初尝试的问题是在student_id(这两个表都有)上缺少一个联接条件。 语法应该是:

select s.* 
from student s 
inner join tutor tt on s.id = tt.student_id 
where tt.code = 's2244'