SQL多表查询和查询一个表中某字段值相同的数据

时间:2021-03-17 15:05:26

如何多表查询,比如A表(student)中有一个字段teacher_id,跟B表(teacher)中的id是相同的。
如果我想查询某个student的teacher,并且要求查询出来的结果包含student的信息和teacher的信息,怎么查询?

select s.id,s.name,t.id,t.name from student  s  left join teacher t on t.id=s.teacher_id;

甚至可以:

select s.id as student_id ,s.name as student_name,t.id as teacher_id,t.name as teacher_name from student  s  left join teacher t on t.id=s.teacher_id;

这样查询出来的结果还未字段指定别名了。

另外,如何查询一个表中某个字段相同的数据?
也是拿student来做例子,查询有相同老师的student。

select * from students group by teacher_id HAVING COUNT(teacher_id)>1;