带有子字符串 WHERE 子句的 SQL 更新查询

发布于 2025-01-10 13:07:48 字数 699 浏览 1 评论 0原文

我有一个名为“引文”的表和一个名为“来源”的表。我想在引文表中创建一个名为“source_id”的外键。引文有一个文本字段“链接”,其中 url 包含至少 7 位长的 ID,距字符串末尾 22 个字符。 Sources 有一个大整数字段“signature”,其中包含至少 7 位长的 ID。我想使用这个 ID 为尽可能多的人创建外键。我稍后会修复 8 位数字长的 ID,可能是手动修复,因为数量应该不多。

当我使用此选择查询时,它仅返回 10 个值(我设置了 10 个条目来匹配,以便我可以测试它),并且 ID 匹配正确。

select s.signature, c.link, s.id, c.id
from citation c, sources s
where right(s.signature, 7) = substring (Reverse(c.link), 22, 7);

但是,当我使用带有相同 where 子句的更新查询时,它会更新引文表中“sources_id”的所有记录。

update citation
set source_id = s.id 
from citation c, sources s
where right(s.signature, 7) = substring (Reverse(link), 22, 7);

我缺少什么?它应该只更新 WHERE 子句子字符串中具有匹配 ID 的 10 条记录。

I have a table called citation and a table called sources. I want to create a foreign key called "source_id" in the citation table. Citation has a text field "link" where the url contains an ID at least 7 digits long, 22 characters from the end of the string. Sources has a big integer field "signature" that contains just that ID at least 7 digits long. I want to use this ID to create a foreign key for as many as possible. The IDs 8 digits long I will fix afterward, probably manually, as there should not be many.

When I use this select query, it returns 10 values only (I had set up 10 entries to match so I could test this), with the correct ID matching.

select s.signature, c.link, s.id, c.id
from citation c, sources s
where right(s.signature, 7) = substring (Reverse(c.link), 22, 7);

However, when I use this update query with the same where clause, it updates all records of "sources_id" in the citation table.

update citation
set source_id = s.id 
from citation c, sources s
where right(s.signature, 7) = substring (Reverse(link), 22, 7);

What am I missing? It should only update the 10 records with matching IDs within the WHERE clause substrings.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

貪欢 2025-01-17 13:07:48

关于UPDATE的手册

不要将目标表重复作为from_item,除非您打算自连接(在这种情况下,它必须与别名一起出现)在 from_item 中)。

所以:

UPDATE citation c
SET    source_id = s.id
FROM   sources s
WHERE  right(s.signature, 7) = substring(reverse(c.link), 22, 7);

奇怪的是,子字符串与 反向 字符串匹配,以及您提到的 8 位数字,但所有这些似乎与问题无关。

The manual about UPDATE:

Do not repeat the target table as a from_item unless you intend a self-join (in which case it must appear with an alias in the from_item).

So:

UPDATE citation c
SET    source_id = s.id
FROM   sources s
WHERE  right(s.signature, 7) = substring(reverse(c.link), 22, 7);

It's odd that the substring matches as reversed string, and what you mention about 8 digits, but all of that seems irrelevant to the question.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文