join two tables and show all records

2019-09-05 04:41发布

问题:

I have two tables in Microsoft Access 2013:

tblService

PART_ID  SERV_DATE   SERV_REMARK  
A0001    11/1/2013   GOOD#1  
A0001    11/13/2013  GOOD#2  
A0001    11/25/2013  GOOD#3

tblWithdraw

PART_ID DRAWN_DATE  DRAWN_REASON  DRAWN_TO  
A0001   11/6/2013   PM            OW601  
A0001   11/20/2013  120 PM        OW603  
A0001   11/30/2013  REPLACEMENT   OW605  

This is the result I want:

PART_ID SERV_DATE   SERV_REMARK  DRAWN_DATE  DRAWN_REASON  DRAWN_TO  
A0001   11/1/2013   GOOD#1       11/6/2013   PM            OW601  
A0001   11/13/2013  GOOD#2       11/20/2013  120 PM        OW603  
A0001   11/25/2013  GOOD#3       11/30/2013  REPLACEMENT   OW605  

But I can get the result neither with INNER JOIN, RIGHT JOIN nor LEFT JOIN. I tried with FULL JOIN, but system prompt me error:

Syntax error in FROM clause

Below is my SQL.

SELECT 
  S.PART_ID, SERV_DATE, 
  SERV_REMARK, DRAWN_DATE, 
  DRAWN_REASON, DRAWN_TO
FROM 
  tblService AS S 
RIGHT JOIN 
  tblWithdraw AS W 
ON 
  S.PART_ID=W.PART_ID;

which shows the result as:

PART_ID SERV_DATE   SERV_REMARK  DRAWN_DATE  DRAWN_REASON  DRAWN_TO  
 A0001  11/1/2013     GOOD#1     11/6/2013        PM         OW601  
 A0001  11/13/2013    GOOD#2     11/6/2013        PM         OW601  
 A0001  11/25/2013    GOOD#3     11/6/2013        PM         OW601
 A0001  11/1/2013     GOOD#1     11/20/2013     120 PM       OW603  
 A0001  11/13/2013    GOOD#2     11/20/2013     120 PM       OW603  
 A0001  11/25/2013    GOOD#3     11/20/2013     120 PM       OW603
 A0001  11/1/2013     GOOD#1     11/30/2013  REPLACEMENT     OW605  
 A0001  11/13/2013    GOOD#2     11/30/2013  REPLACEMENT     OW605  
 A0001  11/25/2013    GOOD#3     11/30/2013  REPLACEMENT     OW605

Can somebody correct my SQL? Or any link to the right code? Thx!

回答1:

You don't have a unique relationship between your two tables and you need one. You will have to restructure your tables (and how data is entered in to them), for example, so that they have a value that makes each instance of a part individual from others with the same PART_ID.

For example:

UID  PART_ID  SERV_DATE   SERV_REMARK  
1    A0001    11/1/2013   GOOD#1  
2    A0001    11/13/2013  GOOD#2  
3    A0001    11/25/2013  GOOD#3

UID  PART_ID  DRAWN_DATE  DRAWN_REASON  DRAWN_TO  
1    A0001    11/6/2013   PM            OW601  
2    A0001    11/20/2013  120 PM        OW603  
3    A0001    11/30/2013  REPLACEMENT   OW605

Then you can modify your SQL to:

SELECT 
  S.PART_ID, SERV_DATE, 
  SERV_REMARK, DRAWN_DATE, 
  DRAWN_REASON, DRAWN_TO
FROM 
  tblService AS S 
RIGHT JOIN 
  tblWithdraw AS W 
ON 
  S.UID=W.UID;

This would give the result you are looking for.