For MS-Access, how do I accomplish following. I was thinking of writing VBA loop but I think it will take a while.
Here are the two tables:
Table A
| id | Day | Month | F_value1
---------------------------------------
| 1 | 10 | 11 | 523
| 1 | 11 | 11 | 955
| 2 | 1 | 11 | 45
| 2 | 2 | 11 | 49
Table B
| id | Day | Month | G_value1
---------------------------------------
| 1 | 10 | 11 | 19923
| 1 | 11 | 11 | 55455
| 2 | 1 | 11 | 45454
What I need:
| id | Day | Month | F_value1 | G_value1
-----------------------------------------------
| 1 | 10 | 11 | 523 | 19923
| 1 | 11 | 11 | 955 | 55455
| 2 | 1 | 11 | 45 | 45454
| 2 | 2 | 11 | 49 | Null
I tried Access Query designer but I had no luck. I'm not sure how to go about it in SQL. I already have table setup.
For programming way, I'm thinking
for each row in Table A
for each row in Table B
If TableA.fields = TableB.fields
Then Insert it into new table
End loop
End loop
You need multiple conditions for the join
s. Fortunately, MS Access supports this with LEFT JOIN
:
SELECT a.id, a.Day, a.Month, a.F_value1, b.G_Value1
FROM TableA as a LEFT JOIN
TableB as b
ON a.ID = b.ID AND a.day = b.day AND a.month = b.month;
You can use INSERT
to insert into an existing table; INTO
to create a new table. Or just run the query to get the results.
In SQL View, this should work and ideally be quicker than your suggested loop
SELECT a.*, b.G_Value1
INTO TableC
FROM TableA a
LEFT JOIN TableB b
ON a.ID=b.ID
If you need full join (ie all records of A and all records of B:
SELECT A.ID, A.Day, A.Month, A.F_value1, B.G_value1
FROM A LEFT JOIN B ON (A.Month= B.Month) AND (A.Day= B.Day) AND (A.ID = B.ID)
UNION
SELECT B.ID, B.Day, B.Month, A.F_value1, B.G_value1
FROM B LEFT JOIN A ON (B.ID = A.ID) AND (B.Day= A.Day) AND (B.Month= A.Month);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.