如何获取记录并避免子查询

时间:2018-01-03 11:37:20

标签: mysql

嗨,我想避免使用子查询,因为它现在非常适合,但将来会很慢。

SELECT 
u.`id`  ,
  u.first_name,
  u.last_name,
  u.username,
  ( SELECT COUNT(*) FROM `complaint` AS p_c WHERE p_c.landlord_id = u.`id` AND p_c.complaint_id = 1  ) AS party_complaints,
  ( SELECT COUNT(*) FROM `complaint` AS r_c WHERE r_c.landlord_id = u.`id` AND r_c.complaint_id = 2  ) AS robery_complaints,
  ( SELECT COUNT(*) FROM `complaint` AS f_c WHERE f_c.landlord_id = u.`id` AND f_c.complaint_id = 3  ) AS fight_complaints,
  ( SELECT COUNT(*) FROM `complaint` AS o_c WHERE o_c.landlord_id = u.`id` AND o_c.complaint_id = 4  ) AS other_complaints,
  COUNT(c.`id`) AS total_complaints_count

FROM
  `user` AS u 
  INNER JOIN complaint AS c 
    ON c.`landlord_id` = u.`id` 

    GROUP BY u.`id` 



    id  first_name  last_name  username   party_complaints  robery_complaints  fight_complaints  other_complaints  total_complaints_count  
------  ----------  ---------  ---------  ----------------  -----------------  ----------------  ----------------  ------------------------
  3591  John        Doe        thefeature                0                 13                 3                 2                        18
  4607  John        Cena       10Fe416l                  2                  1                 0                 1                         4

1 个答案:

答案 0 :(得分:1)

您可以在案例中使用总和

SELECT 
u.`id`  ,
  u.first_name,
  u.last_name,
  u.username,
  sum( case when c.landlord_id = u.`id` and c.complaint_id = 1 then 1 else 0 end)  party_complaints,
  sum( case when c.landlord_id = u.`id` and c.complaint_id = 2 then 1 else 0 end)  robery_complaints,
  sum( case when c.landlord_id = u.`id` and c.complaint_id = 3 then 1 else 0 end)  fight_complaints,
  sum( case when c.landlord_id = u.`id` and c.complaint_id = 4 then 1 else 0 end)  other_complaints
  COUNT(c.`id`) AS total_complaints_count

FROM
  `user` AS u 
  INNER JOIN complaint AS c 
    ON c.`landlord_id` = u.`id` 

    GROUP BY u.`id`