如果另一个表中不存在条目,则将记录插入表中 - 需要额外的处理
向所有强大的 SQL 超级英雄致敬。 谁能将我从迫在眉睫的灾难和毁灭中拯救出来?
我正在使用 Microsoft Access SQL。我想选择一个表(表1)中未出现在另一个表(表2)中的记录..然后将基于表1中的记录的新记录插入到表2中,如下所示:
[表1] file_index : 文件名
[表2] file_index : celeb_name
我想要:
从 table1 中选择所有记录,其中 [filename] 类似于 aud 并且其对应的 [file_index] 值不 存在于 table2 中,其中字段 [celeb_name] = 'Audrey Hepburn'
通过该选择,我想将新记录插入到 [table2]
[file_index] = [table1].[file_index] [celeb_name] = 'Audrey Hepburn'
[table1] 和 [table2] 中的 [file_index] 之间存在一对多关系 [table1] 中有一条记录,[table2] 中有多个记录。
非常感谢
Hi to all you mighty SQLsuperheros out there..
Can anyone rescue me from imminent disaster and ruin?
I'm working with Microsoft Access SQL. I'd like to select records in one table (table1) that don't appear in another (table2) .. and then insert new records into table2 that are based on records in table1, as follows:
[table1]
file_index : filename
[table2]
file_index : celeb_name
I want to:
Select all records from table1 where [filename] is like aud
and whose corresponding [file_index] value does not
exist in table2 with with field [celeb_name] = 'Audrey Hepburn'
With that selection I then want to insert a new record into [table2]
[file_index] = [table1].[file_index]
[celeb_name] = 'Audrey Hepburn'
There is a one to many relationship between [file_index] in [table1] and [table2]
One record in [table1], to many in [table2].
Many thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这行吗?显然添加一些方括号之类的东西。我自己不太喜欢Access。
Will this do? Obviously add some square brackets and stuff. Not too into Access myself.
正如我在评论中所说,NOT IN 并没有被 Jet/ACE 很好地优化,并且使用 OUTER JOIN 通常更有效。在这种情况下,因为您需要在联接的外侧进行过滤,所以您需要一个子查询:(
这可能并不完全正确——我不擅长手动编写 SQL,尤其是正确使用 JOIN 语法)
不过,我必须说,我想知道这是否会插入太多记录(并且相同的保留适用于 NOT IN 版本)。
As I said in comments, NOT IN is not well-optimized by Jet/ACE and it's usually more efficient to use an OUTER JOIN. In this case, because you need to filter on the outer side of the join, you'll need a subquery:
(that may not be exactly right -- I'm terrible with writing SQL by hand, particularly getting the JOIN syntax right)
I must say, though, that I'm wondering if this will insert too many records (and the same reservation applies to the NOT IN version).
您可以使用
NOT Exists
我认为从性能方面来说这是最好的方法。
如下:
You can use
NOT Exists
I think it is the best way from the side of performance.
As Follow:
在最初的问题中,我修改了表和字段名称,并插入了方括号以使其更易于阅读。
下面是以 MS Access 格式运行的最终 SQL 语句。非常棒的结果,再次感谢 Tor!
In the original question I'd modified my table and field names and inserted square brackets in to make it easier to read.
Below is the final SQL statement that worked in MS Access format. Awesome result, thanks again Tor!!