您好,我寻求帮助,以查看我的查询出了什么问题,该查询没有返回来自表consulta的行的计数(数量),其中userIDC等于表用户的userID。与表asesoria中的userIDC相同的操作。

SELECT c.*, SUM(IF(a.userIDA = c.userID , 1, 0)) AS count_asesoria, SUM(IF(s.userIDC = c.userID , 1, 0)) AS count_consulta
   FROM users as c
   LEFT JOIN consulta AS s ON s.userIDC = c.userID
   LEFT JOIN asesoria AS a ON a.userIDA = c.userID
   GROUP BY c.userID DESC


rigt现在对count_asesoriacount_consulta都显示相同的结果

表用户:

userID | Data    |
------------------
3      | content |


表咨询

userIDC | Data   |
------------------
3      | content |
3      | content |


因此count_consulta必须返回2

最佳答案

引起问题的最可能原因是联接中表之间的笛卡尔积。正确的解决方案是在查询之前预先汇总结果。或者,使用相关的子查询。在这种情况下,这可能是最简单的方法,并且可能具有最佳性能:

SELECT u.*,
       (SELECT COUNT(*)
        FROM consulta c
        WHERE c.userIDC = u.userId
       ) as count_consulta,
       (SELECT COUNT(*)
        FROM asesoria a
        WHERE a.userIDA = u.userId
       ) as count_asesoria
FROM users u;


为了获得最佳性能,您需要在consulta(userIDA)asesoria(userIDA)上建立索引。

08-27 16:54