mysql:连接三个表时删除重复

时间:2012-08-10 05:47:01

标签: mysql

我有三个表typemaster,salaryaddition,salarydeduction

typemaster

typeid | typename |

1 | Act.Alw |

2 |食堂|

3 | Sht.Alw |

4 | L.O.P |

salaryaddition

slno | employee | salarytype |金额|

1 | 1 | 1 | 200 |

salarydeduction

员工| salarytype |金额|

1 | 2 | 500 |

1 | 4 | 300 |

我想要显示

员工|加法|金额|扣除|量

1 | Act.Alw | 200 |食堂| 500 |

1 |空|空| L.O.P | 300 |

我写查询但显示重复结果

select a.employee,a.typename,a.amount,b.typename,b.amount from
(select employee,typename,amount from salaryaddition 
 join typemaster on     typeid=salaryaddition.salarytype) a,
(select employee,typename,amount from salarydeduction 
 join typemaster on typeid=salarydeduction.salarytype) b
where a.employee=b.employee

1 个答案:

答案 0 :(得分:0)

鉴于您有员工表,您可以尝试类似

的内容
SELECT  e.employee,
        sat.typename,
        SUM(sa.amount) amount,
        sdt.typename,
        SUM(sd.amount) amount
FROM    employeemaster e LEFT JOIN
        salaryaddition sa   ON  e.employee = sa.employee LEFT JOIN
        typemaster sat  ON  sa.salarytype = sat.typeid LEFT JOIN
        salarydeduction sd  ON  e.employee = sd.employee LEFT JOIN
        typemaster sdt  ON  sd.salarytype = sdt.typeid
GROUP BY    e.employee,
            sat.typename,
            sdt.typename