简体   繁体   English

基于三列联接两个表

[英]Joining two tables based on three columns

For MS-Access, how do I accomplish following. 对于MS-Access,我该如何完成以下操作。 I was thinking of writing VBA loop but I think it will take a while. 我当时在考虑编写VBA循环,但我认为这需要一段时间。

Here are the two tables: 这是两个表:

Table A 表A

 |  id  |   Day  | Month |  F_value1 
 --------------------------------------- 
 |  1   |   10   |   11  |  523 
 |  1   |   11   |   11  |  955 
 |  2   |   1    |   11  |  45
 |  2   |   2    |   11  |  49

Table B 表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. 我尝试使用Access Query设计器,但没有运气。 I'm not sure how to go about it in SQL. 我不确定如何在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. 您需要为多个条件join秒。 Fortunately, MS Access supports this with LEFT JOIN : 幸运的是,MS Access通过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; 您可以使用INSERT插入现有表; INTO to create a new table. INTO创建一个新表。 Or just run the query to get the results. 或者只是运行查询以获取结果。

In SQL View, this should work and ideally be quicker than your suggested loop 在SQL View中,这应该可以正常工作,并且比建议的循环速度更快

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: 如果您需要完全联接(即A的所有记录和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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM