Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/visual-studio-2008/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 如何获取记录并避免子查询_Mysql - Fatal编程技术网

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

Mysql 如何获取记录并避免子查询,mysql,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

嗨,我想避免子查询,因为它现在工作得很好,但将来会变慢

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` 

有一个错误可能是检查它之间的情况下,什么时候?