将查询与exists转换为连接

时间:2018-06-13 18:52:51

标签: mysql sql mysql-workbench

我想以这种方式转换此查询,因此它没有任何“存在”。并且只使用简单的连接。

select  t.Teacher_id, t.Teacher_name, a.marks, a.grade_ID
from Grades a
left join students s on a.student_ID = s.student_ID
left join Teachers t on t.Teacher_ID = s.Teacher_ID
where 1=1 and t.Teacher_id = 1807600
and   exists(
select p.Payment_ID from payments p 
inner join lookups l on (l.lookup_id = p.status_id and l.lookup_key in ('condition1','condition2'))  
where p.student_ID = a.student_ID
)

我尝试过类似的事情:

select  t.Teacher_id, t.Teacher_name, a.marks, a.grade_ID
from Grades a
left join students s on a.student_ID = s.student_ID
left join Teachers t on t.Teacher_ID = s.Teacher_ID
inner join payments p on p.student_ID = a.student_ID
inner join lookups l on (l.lookup_id = p.status_id and l.lookup_key in ('condition1','condition2')) 
where 1=1 and t.Teacher_id = 1807600

但我没有得到正确的结果。你能帮忙吗?感谢。

1 个答案:

答案 0 :(得分:0)

我想你可以使用group by,但是为了不使用EXISTS(),这限制了脚本的可维护性。

select  t.Teacher_id, t.Teacher_name, a.marks, a.grade_ID
from Grades a
left join students s on a.student_ID = s.student_ID
left join Teachers t on t.Teacher_ID = s.Teacher_ID
inner join payments p on p.student_ID = a.student_ID
inner join lookups l on (l.lookup_id = p.status_id and l.lookup_key in ('condition1','condition2')) 
where t.Teacher_id = 1807600
group by  t.Teacher_id, t.Teacher_name, a.marks, a.grade_ID