SQLITE3中的跨表更新
在 SQL Server 中,我可以做这样的事情:
UPDATE tbl1
SET col2 = tbl2.col2
FROM table1 tbl1
INNER JOIN table2 tbl2
ON tbl1.col1 = tbl2.col1
我没有费心去查看这是否是任何 SQL 标准的一部分,而且我确信还有其他方法可以做到这一点,但是它非常有用。
这是我的问题。 我需要使用 SQLITE3 在 SQL(即不是宿主语言)中执行类似的操作。 能做到吗?
In SQL Server
, I can do something like this:
UPDATE tbl1
SET col2 = tbl2.col2
FROM table1 tbl1
INNER JOIN table2 tbl2
ON tbl1.col1 = tbl2.col1
I haven't bothered to look whether this is part of any SQL standard or not, and I'm sure there are other ways to do it, but it is astoundingly useful.
Here's my problem. I need to do something similar in SQL (i.e, not a host language) with SQLITE3. Can it be done?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这适用于 sqlite:
This works for sqlite:
只是为了强调 Geogory Higley 的帖子:
我在使用
UPDATE tbl1 SET col2 = (SELECT col2 FROM tbl2 WHERE tbl2.col1 = tbl1.col1)
时遇到了问题,它更新了 tbl1 中不存在于 tbl2 中的列。请参阅猎豹帖子 http://sqlite.phxsoftware.com/forums/p/ 1708/7238.aspx 指向:
http ://www.mail-archive.com/[email protected]/msg27207.html
代码是:
这似乎才能正常工作。 不同网站上似乎有很多帖子推荐第一种方法,因此有点令人困惑。 如果您使用这种方法,我建议您非常仔细地测试您的输出,这种方法看起来确实更快并且可以与匹配的表一起使用。
Just to emphasize Geogory Higley's post:
I have had problems with
UPDATE tbl1 SET col2 = (SELECT col2 FROM tbl2 WHERE tbl2.col1 = tbl1.col1)
where it updates columns in tbl1 that do not exist in tbl2.see cheetah post at http://sqlite.phxsoftware.com/forums/p/1708/7238.aspx which points to:
http://www.mail-archive.com/[email protected]/msg27207.html
The code is:
and this seems to work correctly. There seem to be many posts at different sites that recommend the first approach so it is a bit confusing. I would suggest you test your output very carefully if you use this method which does seem faster and may work with matched tables.
我发现这可以通过 INSERT OR REPLACE INTO 来完成。 比 T-SQL 的等效项稍微冗长一些,但同样方便。
I've discovered this can be done with
INSERT OR REPLACE INTO
. A little more verbose than T-SQL's equivalent, but just as handy.就其价值而言,Microsoft SQL Server 和 MySQL 是唯一支持多表更新的数据库品牌,并且各自使用的语法并不相似。
此功能不是标准 SQL 的一部分。 因此,对多表更新(和删除)的支持是非标准的并且许多品牌不支持也就不足为奇了。
不管怎样,我很高兴您找到了适合您任务的解决方案。
For what it's worth, Microsoft SQL Server and MySQL are the only brands of database that support multi-table updates, and the syntax each uses is not similar.
This feature is not part of standard SQL. So it's not surprising that support for multi-table update (and delete) is nonstandard and not supported by many brands.
Anyway, I'm glad you found a solution that works for your task.
从版本 3.33 开始,SQLite 支持
UPDATE FROM
习惯用法,但与 SQL Server 的风格略有不同:目标表不得列在FROM
原因中,这意味着与之连接的操作必须在WHERE
子句中完成。你的例子变成:
Since version 3.33, SQLite supports the
UPDATE FROM
idiom, however in a slightly different flavour than that of SQL Server: the target table must not be listed in theFROM
cause, meaning that joins with it must be done in aWHERE
clause.Your example becomes: