如何将新字段插入到与另一个表相关的表中?

时间:2013-12-01 07:31:54

标签: ms-access ms-access-2013

我在MS Access 2013中有两个表。

有一些条件:
1.部件只能在维修后撤回 2.一段时间后,部分将再次退回服务 3.零件可以回收利用。

tblService:

(ID是主键)

ID  PART_ID SERV_DATE
1    A0001  11/1/2013
2    A0001  11/13/2013
3    A0001  11/25/2013
4    B0001  11/26/2013
5    C0001  12/1/2013
6    C0001  12/10/2013
7    C0001  12/20/2013
8    A0001  12/21/2013

tblWithdraw:

(ID是主键)

ID PART_ID DRAWN_DATE DRAWN_REASON DRAWN_TO
1   A0001  11/6/2013       PM         601
2   A0001  11/20/2013    120 PM       603
3   A0001  11/30/2013  REPLACEMENT    605
4   C0001  12/2/2013      30 PM       701
5   C0001  12/15/2013    180 PM       702
6   B0001  12/18/2013      PM         801
7   A0001  12/25/2013     60 PM       502

我想在tblWithdraw中插入一个新字段 SERVICE_ID ,如下所示:
ID PART_ID DRAWN_DATE DRAWN_REASON DRAWN_TO SERVICE_ID
1   A0001  11/6/2013       PM         601       1
2   A0001  11/20/2013    120 PM       603       2
3   A0001  11/30/2013  REPLACEMENT    605       3
4   C0001  12/2/2013      30 PM       701       5
5   C0001  12/15/2013    180 PM       702       6
6   B0001  12/18/2013      PM         801       4
7   A0001  12/25/2013     60 PM       502       8

SERVICE_ID tblService 中的 ID

但是,当我在查询中尝试以下代码时:

INSERT INTO tblWithdraw ( SERVICE_ID ) SELECT ID  

FROM tblService;

它给了我:

ID PART_ID DRAWN_DATE DRAWN_REASON DRAWN_TO SERVICE_ID
1   A0001  11/6/2013       PM         601
2   A0001  11/20/2013    120 PM       603
3   A0001  11/30/2013  REPLACEMENT    605
4   C0001  12/2/2013      30 PM       701
5   C0001  12/15/2013    180 PM       702
6   B0001  12/18/2013      PM         801
7   A0001  12/25/2013     60 PM       502
8                                               1
9                                               2
10                                              3
11                                              4
12                                              5
13                                              6
14                                              7
15                                              8
或者以下代码:

INSERT INTO tblWithdraw (SERVICE_ID) SELECT ID FROM tblService WHERE tblService.PART_ID =tblWithdraw.PART_ID;  

系统无法识别 tblWithdraw.PART_ID

任何人都可以更正我的代码或给我答复或指导我解决方案吗?谢谢!

1 个答案:

答案 0 :(得分:2)

正如您所发现的,INSERT语句总是向表中添加新行。您希望使用以下内容更新现有行:

UPDATE tblWithdraw
SET SERVICE_ID = DLookup("ID","tblService","PART_ID='" & PART_ID & "' AND SERV_DATE=#" & Format(DMax("SERV_DATE","tblService","PART_ID='" & PART_ID & "' AND SERV_DATE<=#" & Format(DRAWN_DATE,"yyyy-mm-dd") & "#"),"yyyy-mm-dd") & "#")

使用DMax()查找给定DRAWN_DATE之前的最新SERV_DATE,然后执行DLookup()查找相应的[tblService]。[ID],然后将其插入SERVICE_ID列在[tblWithdraw]。