SELECT c.id
, c.name
, c.folder
, cs.num_users active_members
, cs.num_videos
FROM campaign c
JOIN campaign_stats cs
ON cs.campaign_id = c.id
JOIN (SELECT _c.id
, _c.name
FROM campaign _c
WHERE _c.type = 9) t_c
ON t_c.id = c.id
WHERE c.id IN (1,2,3)
AND cs.num_videos > 10
This works pretty good for us.
This actual query doesn't make much sense since I tried to build it quickly as an example... but that's not the point.
- t_c stands for category table sub-query or "temp category".
- _underscoring of stuff inside sub-queries.
- alias column names to make sense in the context of the query. e.g. "active_members"
putting commas at the beginning of the new lines makes it easier to build dynamic queries:
$sql .= ", c.another_column"
everything else is straightforward.