我对MySQL有一个非常棘手的问题。
我有两个表有一对多的关系(在相关的列之下)
表A(活动):
id | channel_type | date
表B(预算):
id | campaign_id | budget
我需要单个查询来获取以下结果:
我需要按广告系列表格中的列过滤结果(例如WHERE campaigns.date>' 2014-05-01')
我尝试了以下方法:
SELECT channel_type, COUNT(*) cnt,
(SELECT SUM(budget) FROM budgets WHERE budgets.campaign_id = campaigns.id))
as budget
FROM campaigns
WHERE campaigns.date >= 'some-value'
AND [more conditions]
GROUP BY campaigns.channel_type
但是这当然失败了,因为GROUP我只得到第一个campaign.id结果为channel_type。
任何提示(和解决方案)都会非常感激!
TIA
答案 0 :(得分:0)
答案 1 :(得分:0)
我认为这应该有效:
SELECT channel_type, COUNT(*) cnt,
(SELECT SUM(t2.budget) FROM budgets t2 WHERE t2.campaign_id IN (
SELECT t3.id FROM campaigns t3 WHERE t3.channel_type = t1.channel_type))
AS budget
FROM campaigns t1
WHERE t1.date >= 'some-value'
AND [more conditions]
GROUP BY t1.channel_type
请参阅此fiddle
答案 2 :(得分:0)
我找到了有效的解决方案。 这是工作查询:
SELECT SUM(budget) as budget, COUNT(*) as count FROM
(SELECT * FROM campaigns WHERE [conditions]) AS found_campaigns
LEFT JOIN budgets ON budgets.campaign_id = found_campaigns.id
GROUP BY channel_type