在where子句中使用select in count

时间:2016-10-28 08:47:55

标签: mysql sql

我有这个查询,我正在尝试从修订计划中选择所有必须在本月完成的设备,如果我没有为该设备制作服务单。我想做这样的事情:

select revision_planning.id_echip as echip_id
from revision_planning
    inner join service_sheet on echip_id=service_sheet.id_echip
where revision_planning.next_rev_date between '2016-10-01' and '2016-10-31'
  and count (select * from service_sheet 
             where echip_id=service_sheet.id_echip
               and service_sheet.`data`between '2016-10-01 00:00:00'and '2016-10-31 23:59:18') = 0
  and revision_planning.employee_name='first_last_name'

2 个答案:

答案 0 :(得分:1)

尝试类似:

select revision_planning.id_echip as echip_id from revision_planning
  inner join service_sheet on echip_id=service_sheet.id_echip
  where revision_planning.next_rev_date between '2016-10-01' and '2016-10-31' and not exists (select 1 from service_sheet 
    where echip_id=service_sheet.id_echip and service_sheet.`data`between '2016-10-01 00:00:00'and '2016-10-31 23:59:18')
 and revision_planning.employee_name='first_last_name'

答案 1 :(得分:1)

您可以使用NOT EXISTS语句,而不是在WHERE子句

中检查COUNT = 0
select revision_planning.id_echip as echip_id 
from revision_planning
inner join service_sheet on echip_id=service_sheet.id_echip
where revision_planning.next_rev_date between '2016-10-01' and '2016-10-31' 
and NOT EXISTS(select 1 from service_sheet 
where echip_id=service_sheet.id_echip and service_sheet.`data`between '2016-10-01 00:00:00'and '2016-10-31 23:59:18')
and revision_planning.employee_name='first_last_name'