MYSQL:使用一个表中的不同值左连接两个表

时间:2013-10-25 10:46:29

标签: mysql group-by left-join

我想加入两个具有公共列站代码的表(TABLE vfdefects& tempsubstation)。 问题是tempsubstation有重复的列值,而我只想要每个唯一值的计数。根据我目前的尝试,使用LEFT JOINGROUP BY

将重复条目的值加倍

TABLE A ID|stationID|CODE

TABLE B A|B|C|D|stationcode

查询如下:

SELECT DISTINCT     TS.substationid,'20130924',ts.employeeid,ts.substationcode,ts.manufacturingproductid,ts.assemblylineid,ts.teamid,ts.subofficecode,
TA.AllowID,ta.OtherAllowanceID,ta.allowname,ta.minbenchmark,ta.maxbenchmark,COUNT(vfd.DefectsID) Achieved

FROM tempsubstation ts
LEFT JOIN TempAllowances ta ON ts.manufacturingproductid=ta.manufacturingproductid AND ts.subofficecode=ta.subofficecode AND ta.teamid=ts.teamid
LEFT JOIN wms_assemblyqcmapping aqc ON ts.subofficeid=aqc.subofficeid AND ts.manufacturingproductid=aqc.manufacturingproductid AND ts.assemblylineid=aqc.assemblylineid
LEFT JOIN wms_vfdefects vfd ON vfd.QCStationCode=aqc.QCStationCode AND ts.SubstationCode =vfd.MFGStationNum AND DATE(vfd.CreationDate)='2013-09-24'
WHERE ta.AllowID=42
 GROUP BY ta.minbenchmark,ta.maxbenchmark,ts.substationid
 HAVING COUNT(vfd.DefectsID)>=ta.minbenchmark AND COUNT(vfd.DefectsID)<=ta.maxbenchmark

2 个答案:

答案 0 :(得分:1)

变化:

FROM tempsubstation ts

为:

FROM (SELECT * FROM tempsubstation
      GROUP BY columnWithDuplicateValues) ts

答案 1 :(得分:-1)

您是如何运行查询的?如果通过PHP然后简化SQL并在PHP读取循环中运行第二个SQL。