由于内部连接而显示两次mysql记录

时间:2018-12-12 05:53:24

标签: mysql sql

在下面的查询中,(Mentors)是13,显示我26;而(SchoolSupervisor)是5,显示10是错误的。因为有两个证据的证据,由于两个证据,Mentors&SchoolSupervisor的值使我加倍。 请帮帮我。

查询:

select t.c_id,t.province,t.district,t.cohort,t.duration,t.venue,t.v_date,t.review_level, t.activity, 
        SUM(CASE WHEN pr.p_association = "Mentor" THEN 1 ELSE 0 END) as Mentor, 
        SUM(CASE WHEN pr.p_association = "School Supervisor" THEN 1 ELSE 0 END) as SchoolSupervisor,
        (CASE WHEN count(file_id) > 0 THEN "Yes" ELSE "No" END) as evidence
        FROM review_m t , review_attndnce ra 
        LEFT JOIN participant_registration AS pr ON pr.p_id = ra.p_id 
        LEFT JOIN review_files AS rf ON rf.training_id  = ra.c_id
        WHERE 1=1 AND t.c_id = ra.c_id
        group by t.c_id, ra.c_id order by t.c_id desc

enter image description here

3 个答案:

答案 0 :(得分:0)

您可以在单独的子查询中执行聚合,然后加入该子查询:

SELECT
    t.c_id,
    t.province,
    t.district,
    t.cohort,
    t.duration,
    t.venue,
    t.v_date,
    t.review_level,
    t.activity,
    pr.Mentor,
    pr.SchoolSupervisor,
    rf.evidence
FROM review_m t
INNER JOIN review_attndnce ra
    ON t.c_id = ra.c_id
LEFT JOIN
(
    SELECT
        p_id,
        COUNT(CASE WHEN p_association = 'Mentor' THEN 1 END) AS Mentor,
        COUNT(CASE WHEN p_association = 'School Supervisor' THEN 1 END) AS SchoolSupervisor,
    FROM participant_registration
    GROUP BY p_id
) pr
    ON pr.p_id = ra.p_id
LEFT JOIN
(
    SELECT
        training_id,
        CASE WHEN COUNT(file_id) > 0 THEN 'Yes' ELSE 'No' END AS evidence
    FROM review_files
    GROUP BY training_id
) rf
    ON rf.training_id = ra.c_id
ORDER BY
    t.c_id DESC;

请注意,这还解决了查询中存在的另一个问题,即您选择了许多未出现在GROUP BY子句中的列。在这种重构下,您的当前选择没有任何问题,因为聚合是在单独的子查询中进行的。

答案 1 :(得分:0)

尝试将其添加到查询的WHERE部分

AND pr.p_id IS NOT NULL AND rf.training_id IS NOT NULL

答案 2 :(得分:0)

您可以通过pr.p_id添加一个组,以删除那里的重复记录。由于pr上的分组依据目前不存在,因此对于同一ra

可能存在多个具有相同p_id的记录
group by t.c_id, ra.c_id, pr.p_id order by t.c_id desc