簡體   English   中英

如何獲取記錄並避免子查詢

[英]how to get records and avoid subquery

嗨,我想避免子查詢,因為它現在可以完美地工作,但是將來會變慢。

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

您可以對案件使用總和

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` 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM