2016-12-28 99 views
1

老師表的結果如何獲得MySQL查詢與條件

teacher_id  teacher_name 
============================ 
1    john 
2    doe 

學生表

student_id  student_name student_score teacher_id 
========================================================== 
1    amelia   0    1 
2    anderson  0    1 
3    fabiano   0    1 
4    ronaldo   0    2 
5    peter   6    2 
6    alex   0    2 

結果

teacher_id  teacher_name 
============================ 
2    doe 

結果是老師記錄誰一個或更多的是他的學生得分> 0。

如何查詢這個?

感謝您的回答和對不起我的英文不好

+0

SQL Basic應該可以幫到你。 – Milaci

+0

[Left join with condition]的可能重複(http://stackoverflow.com/questions/9160991/left-join-with-condition) – PereG

+0

選擇t。 teacher_id,T。 teacher_name from teacher t,student's where t.teacher_id = s.teacher_id and s.score> 0. – Milaci

回答

3

一個簡單的子查詢的伎倆

SELECT * FROM teacher WHERE teacher_id IN 
(SELECT teacher_id FROM student WHERE student_score > 0) 

也有可能是內連接

+0

爲什麼使用子查詢而不是單個查詢加入? – Milaci

+0

@ e4c5謝謝先生。我有這個錯誤。在IN語句之前,我使用teacher_id更改了id,它的工作很好。 –

+0

@Milaci出於習慣 – e4c5

1
SELECT teacher.* FROM teacher 
LEFT JOIN student as student teacher.teacher_id = student.teacher_id 
WHERE student.student_score > 0 

希望這會爲你工作。