gpt4 book ai didi

MYSQL 查询带条件选择和连接

转载 作者:行者123 更新时间:2023-11-29 19:44:26 24 4
gpt4 key购买 nike

我有这 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

关于MYSQL 查询带条件选择和连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41132665/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com