Microsoft Access更新查询 - 从另一个表插入主键

时间:2018-01-27 09:33:34

标签: sql ms-access sql-update

Allrighty,因为我对MS Access完全陌生而被困了几天。

我们说我有三张桌子:

  • OrderTable(包含字段:otID作为自动编号的主键,custID,Ref)。
  • CustomerTable(包含字段:custID作为自动编号的主键,custName,custPhone和custEmail)。
  • OP-tMain(包含字段:custName,custPhone,custEmail和Ref)。

所有数据都存储在Excel中,我将使用OperationTable在Access中处理和存储数据。

我可以做UPDATE QUERY来更新CustomerTable就好了。更新CustomerTable后,我需要更新订单表。我面临的问题是,在OrderTable中,我遗漏了custName,custPhone和custEmail,只使用了custID(我认为这是正确的方法)。任何人都可以帮助我如何从OP-tMain更新/插入数据并从CustomerTable中提取相应的cID?

EDIT。此处上传的示例文件==> https://drive.google.com/file/d/1fK3IDEd54Jfr6c-U2s5Bnm4TeK2TQZnM/view

1 个答案:

答案 0 :(得分:0)

考虑使用联接查询进行追加和更新:

追加查询

INSERT INTO OrderTable (CustId, Ref)
SELECT c.CustID, o.Ref
FROM CustomerTable c
INNER JOIN [OP-tMain] o
ON c.custName = o.custName

更新查询以更新参考列,并为每位客户提供多个参考条目的相关计数匹配

UPDATE (OrderTable m
INNER JOIN CustomerTable c ON c.CustID = m.CustID)
INNER JOIN [OP-tMain] o ON c.custName = o.custName
SET m.Ref = o.Ref
WHERE DCOUNT("*", "OrderTable", "otID <=" & m.otID & " AND custID =" & m.custID) = 
      DCOUNT("*", "[OP-tMain]", "ID <=" & o.ID & " AND custName ='" & o.custName & "'")
相关问题