How do i go about matching three fields from two tables in order to update the same tables in case of match
Question
Given two tables A and B in a MySQL Database, how can one update a field in a row of table A if and only if certain fields in the fore-mentioned row in table A exactly match fields in a distinct row of table B. The rows in table B must be used once and only once for each comparison. As such, a row in Table B that has fields matching a row in Table A can not be used a gain to match any other row in Table A.
I have tried
UPDATE
Table A,
Table B
SET
Table A.Status = 'MATCHED',
Table B.Status = 'USED'
WHERE
Table B.Status IS NULL
AND
Table A.Field1 = Table B.Field1
AND
Table A.Field2 = Table B.Field2
Unfortunately, this does not give my desired results since different rows from Table A tend to get matched with the same row in Table B.
For example: Table A
ID Date Ref Amount Status
1 2009-10-20 773 300000
2 2009-10-20 773 10000 MATCHED
3 2009-10-20 773 150000
4 2009-10-20 773 20000 MATCHED
5 2009-10-20 773 140000 MATCHED
Table B
Ref Amount Date ID
870 50000 2009-11-01 1
871 50000 2009-11-01 2
871 80000 2009-11-01 3
871 20000 2009-11-01 4
871 20000 2009-11-01 5
871 20000 2009-11-01 6
872 300000 2009-11-01 7
To match using Ref, Amount and Date.
Solution
Could it be as simple as adding exclusions to the WHERE clause to avoid reuse?
AND Table A.Status <> 'MATCHED'
AND Table B.Status <> 'USED'
This will work if each row is updated in turn, but not if it's set based and transactional. My apologies for not testing this; I don't have MySQL here to try this with.
OTHER TIPS
Add more conditions to your WHERE clause to force a 1:1 match between records in tableA and tableB?