我正在努力成为一个更好的查询作者。我有一个查询,它使用一些子选择来获取数据库中不同表的计数。我不确定它是最有效的方法。我尝试使用 LEFT JOIN 让它更好地工作,但它没有得出正确的结果。
这是“工作”查询:
Select orgID,
(SELECT COUNT(recordID) FROM adoption WHERE orgID = 10031
AND adoptDate BETWEEN '2013-01-01' AND '2013-10-19') as adoptTotal,
(SELECT COUNT(petID) FROM pets WHERE orgID = 10031
AND intakeDate BETWEEN '2013-01-01' AND '2013-10-19') as intakeTotal,
(SELECT COUNT(appID) FROM applications WHERE orgID = 10031
AND applyDate BETWEEN '2013-01-01' AND '2013-10-19') as appTotal,
(SELECT COUNT(appID) FROM `ifosterpets`.`apps`WHERE orgID = 10031
AND dateAdded BETWEEN '2013-01-01' AND '2013-10-19' and isactive = 1) as fosterApps,
(SELECT COUNT(matchID) FROM petmatches WHERE orgID = 10031
AND dateAdded BETWEEN '2013-01-01' AND '2013-10-19' AND isActive = 1) as matchTotals
FROM `memberships`.`orgs`
WHERE orgID = 10031
这是我尝试得到错误结果的方法:
SELECT COUNT(ad.recordID) as adoptTotal, COUNT(p.petID) as intakeTotal, COUNT(a.appID) as appTotal, COUNT(f.appID) as fosterApps, COUNT(m.matchID) as matchTotals
FROM `memberships`.`orgs` o LEFT JOIN adoption ad ON ad.orgID = o.orgID
LEFT JOIN pets p ON p.orgID = o.orgID
LEFT JOIN applications a ON a.orgID = o.orgID
LEFT JOIN `ifosterpets`.`apps` f ON f.orgID = o.orgID
LEFT JOIN petmatches m ON m.orgID = o.orgID
WHERE ad.adoptDate BETWEEN '2013-01-01' AND '2013-10-19'
AND p.intakeDate BETWEEN '2013-01-01' AND '2013-10-19'
AND a.applyDate BETWEEN '2013-01-01' AND '2013-10-19'
AND f.dateAdded BETWEEN '2013-01-01' AND '2013-10-19'
and f.isactive = 1
AND m.dateAdded BETWEEN '2013-01-01' AND '2013-10-19'
AND m.isActive = 1
AND o.orgID = 10031
这是一个两部分的问题:1)我在 LEFT JOIN 查询上做错了什么?2.) 完成第一个查询结果的最有效方法是什么?谢谢!