tags:

views:

309

answers:

2

I want to join two tables together and have ONLY the data in Table 1 (but every record) and add the data from a column in the other table if applicable (there won't be a match for EVERY record)

I tried using a LEFT JOIN matching four columns but I get doubles of some records. If there are 1050 records in table 1 I want 1050 records returned but I get more than that.

Part of the problem is that there aren't any index columns since every column has values that duplicate throughout the column.

Anyway, here is the SQL Statement I tried but I get four extra records (duplicates)

SELECT t1.*, t2.assignedtechnician
FROM idlereport AS t1
LEFT JOIN wipassignedtechnician AS t2
ON (LEFT(t1.rma, 6)=LEFT(t2.rma, 6)
AND t1.receiveddate=t2.receiveddate
AND t1.serial=t2.serial
AND t1.partnumber=t2.partnumber)

P.S. I'm using MySQL

A: 

a left join is the right join in this case, i guess your problem is your on part. why do you join on string columns and not on some index?

nevertheless you should never get more rows than in your left table (idlereport)

knittl
You can easily get more rows if one `idlereport` has more than one matching entry in `wipassignedtechnician` (multiple technicians per report, for example).
Lukáš Lalinský
oh. yes. you are right, i was thinking too fast
knittl
When I started learning about DBs I was not truly aware of the importance of indexed tables and since there was no column that had all unique values in it I didn't create one. There are duplicate values in each column but no record itself is actually duplicated. I wasn't sure using a numerical index would have helped but that was my next step if this question was "unanswerable
Geoff
+1  A: 

Problem is that at times there are more than one record in t2 that matches a single record in t1 based on join conditions you specified...

SELECT t1.*, Min(t2.assignedtechnician)
FROM idlereport AS t1
   LEFT JOIN wipassignedtechnician AS t2
       ON (LEFT(t1.rma, 6)=LEFT(t2.rma, 6)
           AND t1.receiveddate=t2.receiveddate
           AND t1.serial=t2.serial 
           AND t1.partnumber=t2.partnumber)
Group By t1.*

or

SELECT t1.*, 
    (Select Min(t2.assignedtechnician)
     From wipassignedtechnician 
     Where LEFT(rma, 6)=LEFT(t1.rma, 6)
           AND receiveddate=t1.receiveddate
           AND serial=t1.serial 
           AND partnumber=t1.partnumber) assignedtechnician
FROM idlereport AS t1
Charles Bretana
The first one only returned one row? but the second one works, I didn't think of a subquery, still new. Thanks
Geoff