您好我寻求帮助以查看我的查询有什么问题,该查询没有返回表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
现在它为count_asesoria
和count_consulta
表用户:
userID | Data |
------------------
3 | content |
表咨询
userIDC | Data |
------------------
3 | content |
3 | content |
所以count_consulta必须返回2
答案 0 :(得分:0)
问题的最可能原因是连接中表之间的笛卡尔积。正确的解决方案是在查询之前预先聚合结果。或者,使用相关子查询。在这种情况下,这可能是最简单的方法,并且可能具有最佳性能:
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)
上的索引。