如何创建包含当前信息的 mysql 视图

发布于 2024-10-29 06:42:03 字数 313 浏览 4 评论 0原文

我想创建当前信息的视图,如下所示:

CREATE VIEW activeProducts AS SELECT * FROM products WHERE isActive = 1

上面的语句创建查询的快照:

SELECT * FROM products WHERE isActive = 1

因此,如果我在运行此查询后更改表“products”中任何项目的状态,它不会反映在看法。我知道这是mysql中CREATE VIEW的功能,是否应该使用开关或命令来查看或过滤当前信息?

I want to create a view of current information as such:

CREATE VIEW activeProducts AS SELECT * FROM products WHERE isActive = 1

The above statement creates a snapshot of the query:

SELECT * FROM products WHERE isActive = 1

So if I change the state of any item in the table 'products' after this query is run, it isn't reflected in the view. I understand that this is the function of CREATE VIEW in mysql, is there a switch or command that I should use for viewing or filtering current information?

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

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

发布评论

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

评论(2

半城柳色半声笛 2024-11-05 06:42:03

您正在寻找的东西称为物化视图

MySQL 本身不支持物化视图。

有一些解决方法,但最简单直接(如果性能不佳)是使用 CREATE TABLE ... AS SELECT ... 而不是创建视图。这会复制数据,如果数据很多,速度可能会很慢。此外,我不相信它会创建任何索引,因此您可能需要稍后进行清理。

The thing you're looking for is called a materialized view.

MySQL does not natively support materialized views.

There are a few workarounds, but the most simple and straightforward (if poor performing) is using CREATE TABLE ... AS SELECT ... instead of creating a view. This duplicates data, and may be quite slow if there's a lot of it. Further, I don't believe it creates any indexes, so you might need to clean up a bit afterward.

帝王念 2024-11-05 06:42:03

您想要的是“物化视图”,也称为快照。

查尔斯提出了拍摄快照的最简单方法,但正如他所建议的那样,它不会有索引。如果您希望快照包含相同的索引,您可以使用:

create table if not exists snapshot_table like regular_table;
begin; 
  delete from snapshot_table; 
  insert into snapshot_table select * from regular_table where isActive = 1;
commit;

也就是说,如果表很大,或者您想使用联接或聚合,那么更新视图可能会非常昂贵。

如果您想研究可以快速刷新的“增量可刷新物化视图”,请查看 此博文

What you want is a "materialized view" which is also known as a snapshot.

Charles presented the easiest way to take a snapshot, but as he suggested it won't have indexes. If you want the snapshot to include the same indexes you can use:

create table if not exists snapshot_table like regular_table;
begin; 
  delete from snapshot_table; 
  insert into snapshot_table select * from regular_table where isActive = 1;
commit;

That being said, if the table is large, or you want to use joins or aggregation, then updating the view can be very expensive.

If you want to investigate "incrementally refreshable materialized views", which can be refreshed fast, then check out this blog post.

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