Fetching data after left join query by removing duplicates?
I used a left join query with two tables so I'm getting multiple values for the main table column value in the resultset. How can I remove duplicates in that?
Query:
SELECT cc.CCODE, cc.CNAME, rc.RCODE, rc.RNAME
FROM RCODE AS rc
LEFT JOIN CCODE AS cc ON cc.RCODE 开发者_JS百科= rc.RCODE
GROUP BY cc.ccode
For rc.RCODE
I get duplicate values if there is more than 1 entry for this in the child table. Once I get the resultset, how can I remove that in code level?
first table -->RCODE INDIA PAKISTAN AMERICA second table --> RCODE CCODE INDIA KERALA INDIA KARNATAKA AMERICA TEMP I need to get INDIA ->and its CCODE ANERICA its CCODE PAKISTAN its CCODE -> if its null ok ineed to get RCODE
Your question is not as clear as it could be, but if you want to have one row in the result set for each row in the RCode table, with at most one row of information from the CCode table, then you should write your query to generate exactly what you want rather than tinkering with the result set after fetching the data. Since you need one row from CCode table per RCode value, we can use:
SELECT cc.CCode, cc.CName, rc.RCode, rc.RName
FROM RCode AS rc
LEFT JOIN (SELECT c1.CCode, c1.RCode, c1.CName
FROM CCode AS c1
JOIN (SELECT c2.RCode, MAX(c2.CCode) AS CCode
FROM CCode AS c2
GROUP BY c2.RCode) AS c3
ON c1.CCode = c3.CCode AND c1.RCode = c3.RCode
) AS cc
ON cc.RCode = rc.RCode
The innermost sub-query (tagged c3) gives you the maximum CCode for each RCode in the CCode table. When this is joined with the CCode table, it gives you the corresponding CName too. This result set (tagged cc) is left outer joined with the RCode table, but there is at most one row in the cc result set for each RCode unless it so happens that the CCode tables contains several rows with the same RCode and the maximum CCode value. If that is a problem, then you need to find an alternative mechanism to give you one row from the CCode table per RCode value (maybe MAX(CName)
instead of MAX(CCode)
).
精彩评论