表mpkids_students AS A
id BranchId Email Mobile StudentId
9497 25 mpsuraj2016@gmail.com 8700698773 25
9498 25 m016@gmail.com 8700698776 26
表mpkids_student_image_gallery AS B
id like_count student_id
1 25 27
表mpkids_visitors AS C
id student_id
1 9497
2 9497
3 9497
表mpkids_visitors_count AS D
id visitor_count student_id
1 4 23
表mpkids_image_likes AS E
id student_id
1 67
表mpkids_relatives_data AS F
id student_id rel_email rel_mobile
1 9497 kushwahji@gmail.com 9009859691
2 9497 kushwah@gmail.com 7566403326
3 9497 kushwah@gmail.com 1236403326
4 9497 suraj@gmail.com 123640332
表mpkids_paidstatus AS G
id student_id Received
1 9497 7500
2 9497 3000
3 9497 3000
MYSQL查询
SELECT A.id as student_id,
COUNT(DISTINCT B.id) as images,
COUNT(DISTINCT C.id)+ COUNT(DISTINCT D.visitor_count) as visits,
count(DISTINCT E.id) + SUM(B.like_count) as likes,
COUNT(DISTINCT A.Email)+COUNT(DISTINCT F.rel_email) as emails,
COUNT(DISTINCT A.Mobile)+COUNT(DISTINCT F.rel_mobile) as moibles,
SUM(G.Received) as Received
FROM mpkids_students AS A
LEFT JOIN mpkids_student_image_gallery AS B ON B.student_id = A.id
LEFT JOIN mpkids_visitors AS C ON C.student_id = A.id
LEFT JOIN mpkids_visitors_count AS D ON D.student_id = A.id
LEFT JOIN mpkids_image_likes AS E ON E.student_id = A.id
LEFT JOIN mpkids_relatives_data AS F ON F.student_id = A.id
LEFT JOIN mpkids_paidstatus AS G ON G.student_id = A.id
WHERE A.BranchId = 25
GROUP BY A.id
ORDER BY A.StudentId DESC
结果:
student_id images visits likes emails moibles Received
9497 0 3 NULL 4 5 202500
9498 0 0 NULL 1 1 NULL
问题说明:
Received Field返回错误的值,我尝试了许多查询,但没有得到解决方案 学生编号= 9497的接收字段正确值13500 请帮助我找到解决方法。
答案 0 :(得分:0)
输出错误的原因是,当您基于Studentid加入时,您会从mpkids_paidstatus
表中为每个学生获取多个记录,这将累加并返回错误的输出。
您还可以像使用子查询一样编写查询。
SELECT A.id as student_id,
COUNT(DISTINCT B.id) as images,
COUNT(DISTINCT C.id)+ COUNT(DISTINCT D.visitor_count) as visits,
count(DISTINCT E.id) + SUM(B.like_count) as likes,
COUNT(DISTINCT A.Email)+COUNT(DISTINCT F.rel_email) as emails,
COUNT(DISTINCT A.Mobile)+COUNT(DISTINCT F.rel_mobile) as moibles,
(select SUM(Received) from mpkids_paidstatus ps where ps.student_id=a.id) as Received
FROM mpkids_students AS A
LEFT JOIN mpkids_student_image_gallery AS B ON B.student_id = A.id
LEFT JOIN mpkids_visitors AS C ON C.student_id = A.id
LEFT JOIN mpkids_visitors_count AS D ON D.student_id = A.id
LEFT JOIN mpkids_image_likes AS E ON E.student_id = A.id
LEFT JOIN mpkids_relatives_data AS F ON F.student_id = A.id
WHERE A.BranchId = 25
GROUP BY A.id
ORDER BY A.StudentId DESC