2016-12-13 33 views
0

我試圖讓這個查詢工作,這是我的邏輯,我想選擇記錄那沒有至少沒有這些選項之一:在MYSQL多不exsits檢查的行數

1). status = Approved AND end_date >now 
2). status =Approved AND end_date is NULL 
3). status = Pending And end_date is NULL & COUNT(id) =1 
4). status =Pending AND end_date >now & COUNT(id) =1 
5). status =Pending AND end_date <now & COUNT(id) =1 

如何做到這一點,這是我迄今爲止我不知道如何檢查COUNT(id)= 1條件3,4和5?

SELECT 
    * 
FROM 
    outreach 
WHERE 
    NOT EXISTS (
     SELECT 
      * 
     FROM 
      outreach_links 
     WHERE 
      outreach_links.outreach_id = outreach.id 
     AND STATUS = "Approved" 
     AND end_date > now() 
    ) 
AND NOT EXISTS (
    SELECT 
     * 
    FROM 
     outreach_links 
    WHERE 
     outreach_links.outreach_id = outreach.id 
    AND STATUS = "Approved" 
    AND end_date IS NULL 
) 
AND NOT EXISTS (
    SELECT 
     * 
    FROM 
     outreach_links 
    WHERE 
     outreach_links.outreach_id = outreach.id 
    AND STATUS = "Pending" 
    AND end_date > now() 
) 
AND NOT EXISTS (
    SELECT 
     * 
    FROM 
     outreach_links 
    WHERE 
     outreach_links.outreach_id = outreach.id 
    AND STATUS = "Pending" 
    AND end_date IS NULL 
) 
AND NOT EXISTS (
    SELECT 
     * 
    FROM 
     outreach_links 
    WHERE 
     outreach_links.outreach_id = outreach.id 
    AND STATUS = "Pending" 
    AND end_date < now() 
) 

回答

0
select 
    o.*, 
    SUM(if(ol.status = "Approved" and (ol.end_date > now() or end_date is null), 1, 0)) as cond1, 
    SUM(if(ol.status = "Pending" and (ol.end_date != now() or end_date is null), 1, 0)) as cond2 
from 
    outreach o 
left join 
    outreach_links ol on ol.outreach_id = o.id 
group by 
    o.id 
having 
    cond1 = 0 and cond2 != 1 
; 

不知道如果這就是你要找的,但你可以試試。 cond2!= 1會讓您的COUNT(id)= 1條件(如果outreach_links中有多個鏈接的id,cond2將大於1)

+0

wuar is!= now?我沒有那種條件,我>>或更少或爲空 – user3150060

+0

,因爲4)>現在,5)<現在和3)非空。這給了我們!= now ... l – Alexey

+0

我得到它的工作,但我的問題,如果我想從MAX(ol.end_date)選擇ol.cost,我該怎麼做? – user3150060