簡體   English   中英

MYSQL查詢選擇條件並加入

[英]MYSQL Query Select with condition & Join

我有這3個表(具有這些結構):

        outreach
        id  url              profile_id
------------------------------------------
        40  www.google.com     2
        41  www.yahoo.com      3
        42  www.test.com       1

        outreach_links
        id outreach_id end_date           status 
    -----------------------------------------------
        1   41          2016-01-12        Pending
        2   40          2016-03-12        Pending
        3   40          2016-02-12        Approved

        comments
        id outreach_id  name
    ----------------------------
        1   40
        2   40
        3   40

我有這個查詢:

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,
SUM(if(ol.status = "Pending" and (ol.end_date < now()), 1, 0)) as cond3
from outreach o 
left join outreach_links ol on ol.outreach_id = o.id 
where o.profile_id=2
group by o.id
having (cond1 = 0 and cond2 = 0) or (cond1 = 0 and (cond2 = 1 and cond3 >=1)) order by ol.end_date desc

我正在嘗試修復此查詢,並使其也選擇以下內容:

1). ol.* ONLY if MAX(end_date) and
2). Count(id.comment) count all comments for that particular row

那可能嗎?

現在這里是輸出

+"id": "40"
+"profile_id": "2"
+"url": "http://www.google.com"
+"created_at": "2016-12-05 21:55:10"
+"updated_at": "2016-12-05 22:49:56"
+"cond1": "0"
+"cond2": "0"
+"cond3": "5"

我要添加

+"max_date": get me max of end_date and the whole row of the row highlighted 
+"Count(comments)": get me all the comments count for this one which is 3

謝謝

您是否要獲取最新的更新日期? 以下查詢應為您提供最新的更新日期。

但是,我不明白您要為cond1,cond2,cond3嘗試獲得什么,應將什么填充為created_date和updated_date? 您能為這些字段給出定義嗎?

SELECT o.*, ol.*, COUNT(c.id)
FROM outreach o 
LEFT JOIN outreach_links ol ON ol.outreach_id = o.id
LEFT JOIN comments c ON c.outreach_id = o.id
WHERE ol.id = (SELECT ol2.id
                 FROM outreach_links ol2
                 WHERE ol2.outreach_id = ol.outreach_id            
                 ORDER BY ol2.end_date, ol2.id DESC
                 LIMIT 1)
      OR ol.id IS NULL
GROUP BY o.id, ol.id

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM