我有一个名为Ads的表格,每个广告都包含一行。
| ID | AdTitle | AdDescription | ...... |
我还有3个名为“应用程序”,“推荐人”和“订阅者”的表,每个应用程序的行数,推荐人和订阅者与广告相关联。
| ID | AdID |申请人姓名|申请人电子邮件| ...... |
| ID | AdID | ReferrerEmail | ReferralEmail | ...... |
| ID | AdID | SubscriberEmail | ...... |
最后,我有一个名为Views的表格,每个广告都有一行,包含该广告的总观看次数。
| ID | AdID |意见|
我正在尝试使用6列中的每个广告的摘要编写查询:广告ID,广告标题,应用/推介/订阅者数量和总观看次数。
对我一直在使用的所有表的简单查询:
SELECT *
FROM Ads
LEFT JOIN Applications ON Ads.ID = Applications.AdID
LEFT JOIN Referrals ON Ads.ID = Referrals.AdID
LEFT JOIN Subscribers ON Ads.ID = Subscribers.AdID
LEFT JOIN Views ON Ads.ID = Views.AdID
我尝试了很多LEFT和INNER联接,GROUP BY,COUNT(...),COUNT(DISTINCT ......)和SUM(CASE ......)的组合,但到目前为止还没有任何效果。我最终计算前一列中的NULL值,计数两次或完全不计数,计算Views-table中的行数而不是将它们一起添加等等。
将它分解为多个查询是否更好,或者是否有一种很好的方法可以将我想要的内容归档为一个?
答案 0 :(得分:0)
试试这个
SELECT *,
(select count (*) from Applications as A1 where A.ID = A1.AdID ) as Applicants,
(select count(*) from Referrals as R where A.ID = R.AdID ) as Referrals,
(select count(*) from Subscribers as S where A.ID = S.AdID ) as Subscribers,
(select count(*) from Views as V where A.ID = V.AdID ) as Views
FROM Ads as A