2016-10-28 81 views
1

我有這個查詢,我試圖從修訂計劃中選擇所有必須在本月完成的設備,如果我沒有爲該設備製作服務表。我想要做這樣的事情:在where子句中使用select中的計數

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' 
+0

我爲COUNT = 0檢查聲明使用MySQL。 –

回答

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

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

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' 
+0

我相信,在不存在'select 1'會比'select *'更優化 – NzGuy

+0

是的,但是如果表格很大,會發現差異 –

+0

@NzGuy:這是一個從未如此的神話。在任何現代數據庫管理系統中,'select 1'和'select *'之間沒有任何性能差異(並且從來沒有 - 至少不是在這個千年中) –