[英]MYSQL: left join in two tables using distinct value from one table
我想加入兩個具有公用列stationcode(TABLE vfdefects&tempsubstation)的表。 問題是tempsubstation具有重復的列值,而我只想要每個唯一值的計數。 以我目前的嘗試,它使用LEFT JOIN
和GROUP 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
更改:
FROM tempsubstation ts
至:
FROM (SELECT * FROM tempsubstation
GROUP BY columnWithDuplicateValues) ts
您如何運行查詢? 如果通過PHP,則簡化SQL,並在PHP讀取循環中運行第二個SQL。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.