MYSQL在一个重复结果

时间:2015-10-16 12:46:02

标签: mysql subquery

我有一些子查询的查询。

表示子查询在那里工作正常,但是当在一个大查询中放在一起时,返回的结果就会重复。

查询:

SELECT
kpi.kra_id AS kra,
kpi.id AS kpi, 
(
    SELECT 
    ROUND(AVG(sp.progress), 2) 
    FROM `submissions` AS sub
    LEFT JOIN `sub_performancemeasures` sp ON sp.sub_id = sub.id
    WHERE sub.programme = 'programme' 
    AND sub.submission_year = '2015/2016' 
    AND sub.state = '2'
    AND sub.period = '1'
    AND pm.kpi_id = kpi.id
) AS p1_programme_score,
(
    SELECT 
    ROUND(AVG(sp.progress), 2) 
    FROM `submissions` AS sub
    LEFT JOIN `sub_performancemeasures` sp ON sp.sub_id = sub.id
    WHERE sub.programme = 'programme' 
    AND sub.submission_year = '2015/2016' 
    AND sub.state = '2'
    AND sub.period = '2'
    AND pm.kpi_id = kpi.id
) AS p2_programme_score
FROM `kpis` kpi
LEFT JOIN `performance_measures` pm ON kpi.id = pm.kpi_id
GROUP BY kpi.id 

结果如下:

MySQL Results

我正在寻找的是每个KPI,以显示每个p1和p2列的自己的分数。

2 个答案:

答案 0 :(得分:1)

我不知道如何解决问题,因为您没有包含数据结构。但是,我可以找出可能的原因。

每个子查询都有这样的条件:

AND pm.kpi_id = kpi.id

子查询中都没有pmkpi,因此这只会重复外部查询中的join条件。据推测,您希望kpi_id匹配子查询中的某些表,subsp

答案 1 :(得分:0)

确实非常感谢JerodevxQBert让我指向正确的方向。新的工作查询如下:

SELECT
kpi.kra_id AS kra,
kpi.id AS kpi, 
(
    SELECT 
    ROUND(AVG(sp.progress), 2) 
    FROM `submissions` AS sub
    LEFT JOIN `sub_performancemeasures` sp ON sp.sub_id = sub.id
    LEFT JOIN `performance_measures` pm ON pm.id = sp.pm_id
    WHERE sub.programme = 'programme' 
    AND sub.submission_year = '2015/2016' 
    AND sub.state = '2'
    AND sub.period = '1'
    AND pm.kpi_id = kpi.id
) AS p1_programme_score,
(
    SELECT 
    ROUND(AVG(sp.progress), 2) 
    FROM `submissions` AS sub
    LEFT JOIN `sub_performancemeasures` sp ON sp.sub_id = sub.id
    LEFT JOIN `performance_measures` pm ON pm.id = sp.pm_id
    WHERE sub.programme = 'programme' 
    AND sub.submission_year = '2015/2016' 
    AND sub.state = '2'
    AND sub.period = '2'
    AND pm.kpi_id = kpi.id
) AS p2_programme_score
FROM `kpis` kpi
GROUP BY kpi.id 

此查询的不同之处在于performance_measures表的连接位置。它是在主要查询上,但它需要绑定到子查询,所以我移动它和VIOLA!