我正在为我的网站用户构建一个统计页面,以查看他们与各种功能的交互程度。他们可以在网站上进行四种不同类型的活动,为他们获取积分,并向其他用户提供有关其答案的反馈。这些都记录在数据库中。
我遇到的问题是,只有两种类型的联接才能获得预期的输出,即INNER JOIN和LEFT JOIN,它们具有截然不同的执行时间。
我敢肯定,因此我在这里缺少效率步骤,或者在这种情况下误解了联接的用法。我可以使用帮助查看SQL语句并查看如何进行改进。
中提琴链接:http://sqlfiddle.com/#!9/9dce51(由于大小限制,数据有限!)
问题在于下面的八组-其他查询迅速且正确地执行。
SELECT users.forename, users.surname, users.email,
users_peer_request.user_id, COUNT(DISTINCT users_peer_request.id) as peer_req_cnt,
COUNT(DISTINCT users_self_assessment.id) AS self_assess_cnt, AVG(users_self_assessment.assessment) AS self_assess_avg,
GROUP_CONCAT(DISTINCT classes.name, '-', classes.id SEPARATOR ',') AS classes,
COUNT(DISTINCT a_experiment_points.id) AS tried_exp,
COUNT(DISTINCT a_phetlabs_points.id) AS tried_phet,
COUNT(DISTINCT a_videonotes_points.id) AS tried_video,
COUNT(DISTINCT a_working_points.id) AS tried_work,
COUNT(DISTINCT a_experiment_feedback.id) AS fb_exp,
COUNT(DISTINCT a_phetlab_feedback.id) AS fb_phet,
COUNT(DISTINCT a_videonotes_feedback.id) AS fb_video,
COUNT(DISTINCT a_working_feedback.id) AS fb_work
FROM users_peer_request
LEFT JOIN classes ON classes.id IN (SELECT classes_students.class_id FROM classes_students WHERE classes_students.student_id = users_peer_request.user_id)
LEFT JOIN users ON users.gid = users_peer_request.user_id
LEFT JOIN users_self_assessment ON users_self_assessment.user_id = users_peer_request.user_id
INNER JOIN a_experiment_points ON a_experiment_points.user_id = users_peer_request.user_id
INNER JOIN a_phetlabs_points ON a_phetlabs_points.user_id = users_peer_request.user_id
INNER JOIN a_videonotes_points ON a_videonotes_points.user_id = users_peer_request.user_id
INNER JOIN a_working_points ON a_working_points.user_id = users_peer_request.user_id
INNER JOIN a_experiment_feedback ON a_experiment_feedback.user_fb_id = users_peer_request.user_id
INNER JOIN a_phetlab_feedback ON a_phetlab_feedback.user_fb_id = users_peer_request.user_id
INNER JOIN a_videonotes_feedback ON a_videonotes_feedback.user_id_fb = users_peer_request.user_id
INNER JOIN a_working_feedback ON a_working_feedback.user_fb_id = users_peer_request.user_id
WHERE users_peer_request.user_id = 123456789123456789123456
GROUP BY users_peer_request.user_id
此查询运行在小提琴上,但我希望返回NULL或0(其中用户未出现在表中),以及一个否则将对该值进行计数的数字。
非常感谢,希望您在这里有足够的详细信息,如果没有,请询问:)