mysql查询没有给出准确的结果

时间:2015-12-08 10:24:40

标签: mysql sql

我正在研究一个查询,其目的是获取所有学生的记录,其中financialyear_id!= 4并且不显示记录,即使他/她有finacialyear_id,然后存在4。 我写了一个查询,但是它给了我那个学生的记录,其中finacialyear_id!= 4但是我想要实现,如果任何学生都存在financialyear_id = 4,就不会显示任何记录。

SELECT a.id aid
     , s.id sid
     , s.name
     , s.father_name
     , s.cnic
     , f.financialyear_id 
  FROM student s 
  JOIN academic_info a 
    ON a.s_id = s.id
  LEFT 
  JOIN fee_issued f 
    ON a.id = f.academic_info_id
 WHERE f.financialyear_id != 4 
   AND a.is_data_locked = 0 
   AND a.university_id = 60;

外键:两个表中的s_id:academic_info和fee_issued,academic_info_id在fee_issued表中。

1 个答案:

答案 0 :(得分:0)

您在请求中使用了关键字:"但我想要实现,如果任何学生的financialyear_id = 4 存在,则不会显示任何记录。"因此,请使用EXISTS(或大约相同的IN来检查是否存在。

当您使用MySQL时,您必须为academic_info写两次选择条件。其他DBMS更优雅地处理这个问题。

select a.id as aid, s.id as sid, s.name, s.father_name, s.cnic, f.financialyear_id
from student s
join academic_info a on a.s_id = s.id and a.is_data_locked = 0 and a.university_id = 60
left join fee_issued f on f.academic_info_id = a.id
where s.id not in
(
  select ai.s_id
  from academic_info ai
  join fee_issued fi on fi.academic_info_id = ai.id and fi.financialyear_id != 4
  where ai.is_data_locked = 0 and ai.university_id = 60
);

以上查询还可以为您提供完全没有费用的学生。如果要删除这些,请将左连接更改为内连接。

编辑:这与NOT EXISTS相同。

select a.id as aid, s.id as sid, s.name, s.father_name, s.cnic, f.financialyear_id
from student s
join academic_info a on a.s_id = s.id and a.is_data_locked = 0 and a.university_id = 60
left join fee_issued f on f.academic_info_id = a.id
where not exists
(
  select *
  from academic_info ai
  join fee_issued fi on fi.academic_info_id = ai.id and fi.financialyear_id != 4
  where ai.is_data_locked = 0 and ai.university_id = 60
  and ai.s_id = s.id
);