选择第一个记录到field1,将其他记录选入field2

时间:2016-01-27 16:47:07

标签: sql ms-access

我有一个带有id的 table1 。另一个 table2 有两个字段; 主人孩子

我需要在 table2 中选择 table1 中的第一个ID 作为 master ,然后 table2 中的其他ID

1 我试过这个:

Dim rs as recordset
Dim strSql as String  

strSql = "Select top 1 Id FROM table1"           
Set rs = CurrentDb.OpenRecordset(strSql)
rs.MoveFirst
strSql = "INSERT INTO table2 (child) SELECT table1.Id FROM table1 WHERE Id <> " & rs.Fields(0).Value
DoCmd.RunSQL strSql
strSql = "UPDATE table2 SET master = " & rs.Fields(0).Value & " WHERE master is null"
DoCmd.RunSQL strSql 
rs.Close
Set rs = Nothing

但是因为我必须在代码中多次为不同的表做同样的事情,所以如果可能的话,我宁愿用一个查询来做。如果可能,也可以没有子查询。

1 个答案:

答案 0 :(得分:0)

您可以使用类似的东西,假设您的ID是数字列

with

如果没有子查询,我没有办法做到这一点。

相关问题