内部联接消除了重复

时间:2016-03-27 13:27:10

标签: mysql sql inner-join

架构: enter image description here

查询:

 SELECT avto.Marka,SUM(OtrabotanoMachine_hours) as 'work hours',SUM(sec.Hours) as Downtime,CONVERT(group_concat(concat(prostoy.Prichina,'=',sec.Hours) separator ';') USING 'utf8') as 'downtime reasons',CONVERT(group_concat(concat(VipolnennayaRabota,'=',V_raboty) separator ';') USING 'utf8') as 'performed works'
FROM
jos_addRabotyAndProstoyMain main 
INNER JOIN avto ON main.Marka=avto.ID_Avto
INNER JOIN (
   SELECT id_fk, SUM(Hours) AS Hours, Prostoy
   FROM jos_addRabotyAndProstoySecond 
   GROUP BY id_fk,Prostoy) sec ON sec.id_fk = main.id 
INNER JOIN prostoy ON sec.Prostoy = prostoy.ID_Prosyoy
GROUP BY avto.Marka

错误的结果:

 | Marka   | work hours  |downtime| downtime reasons      | performed works|
 |JCB-90QX |      44     |    7   |lack of materials=2;   | work=51;       |
 |         |             |        |machine malfunction=1; | work=51;       |               
 |         |             |        |Others=3;              | work=51;       |
 |         |             |        |unscheduled repairs=1  | work=51;       |

列“工作时间”和“已执行工作”包含重复项。如何消除重复?

我需要这样的结果:

| Marka   | work hours  |downtime| downtime reasons      | performed works|
|JCB-90QX |      11     |    7   |lack of materials=2;   | work=51;       |
|         |             |        |machine malfunction=1; |                |               
|         |             |        |Others=3;              |                |
|         |             |        |unscheduled repairs=1  |                |

更新SQL Fiddle

1 个答案:

答案 0 :(得分:1)

我认为解决方案是在要使用唯一数据的列中添加DISTINCT子句。

试试这个(取自你的SQL小提琴):

 SELECT avto.Marka,SUM(distinct OtrabotanoMachine_hours) as 'work hours',SUM(sec.Hours) as Downtime,CONVERT(group_concat(concat(prostoy.Prichina,'=',sec.Hours) separator ';') USING 'utf8') as 'downtime reasons',CONVERT(group_concat(distinct concat(VipolnennayaRabota,'=',V_raboty) separator ';') USING 'utf8') as 'performed works'
FROM
jos_addRabotyAndProstoyMain main 
INNER JOIN avto ON main.Marka=avto.ID_Avto
INNER JOIN (
   SELECT id_fk, SUM(Hours) AS Hours, Prostoy
   FROM jos_addRabotyAndProstoySecond 
   GROUP BY id_fk,Prostoy) sec ON sec.id_fk = main.id 
INNER JOIN prostoy ON sec.Prostoy = prostoy.ID_Prosyoy
GROUP BY avto.Marka

但是,请务必注意,我并非100%确定如何设置OtrabotanoMachine_hours。如果有两个合法的单独条目具有相同的值,它将对它们进行重复数据删除。