SELECT `apps`.*,
COUNT(all_users.id) AS total_users,
COUNT(active_users.id) AS active_users
FROM `apps`
INNER JOIN `social_users` AS `all_users` ON `all_users`.`app_id` = `apps`.`id`
INNER JOIN `social_users` AS `active_users` ON `active_users`.`app_id` = `apps`.`id`
WHERE `active_users`.`is_active` = 'true'
GROUP BY `id`
ORDER BY `total_users` ASC LIMIT 30
OFFSET 0
我有 2 个表。
apps -> id, name
social_user -> id, app_id, is_active
我想在 apps 表上运行查询并显示所有总用户数和所有活跃用户数。
我两次加入 social_users。
问题是,如果我加入一次(无论是哪个),它运行得非常快。第二次加入会破坏性能并且数字根本不准确,我得到 180000 个用户而不是 750 个。
我怎样才能做得更好更快?
谢谢
最佳答案
SELECT `apps`.*,
COUNT(all_users.id) AS total_users,
SUM(IF(all_users.is_active='true',1,0)) AS active_users
FROM `apps`
INNER JOIN `social_users` AS `all_users` ON `all_users`.`app_id` = `apps`.`id`
GROUP BY `id`
ORDER BY `total_users` ASC LIMIT 30
OFFSET 0
关于mysql两次加入同一张表运行速度很慢,结果错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39195292/