简体   繁体   English

我可以在 MySql 中的临时表上创建视图吗?

[英]Can I create a view on a temporary tables in MySql?

Is it possible to create a view on a temporary table in MySql?是否可以在 MySql 中的临时表上创建视图?

@O Jones, what you are searching is "The Variable Table" @O Jones,您正在搜索的是“变量表”

MySql : MySql

CREATE TEMPORARY TABLE TempTableName (
 column_1 DATATYPE ARGUMENTS, 
 column_2 DATATYPE ARGUMENTS, 
 column_N DATATYPE ARGUMENTS
); 

Here is an example on how to use it这是有关如何使用它的示例

CREATE TEMPORARY TABLE WeekDays(
  WeekNumber INT NOT NULL,
  ShortWeekDayName VARCHAR(40) NOT NULL, 
  WeekDayName VARCHAR(40) NOT NULL
);
 
INSERT INTO WeekDays
VALUES 
(1,'Mon','Monday')  ,
(2,'Tue','Tuesday') ,
(3,'Wed','Wednesday') ,
(4,'Thu','Thursday'),
(5,'Fri','Friday'),
(6,'Sat','Saturday'),
(7,'Sun','Sunday'); 

SELECT * FROM WeekDays;

MSSQL :微软SQL

DECLARE @table_variable_name TABLE (
 column_1 DATATYPE ARGUMENTS, 
 column_2 DATATYPE ARGUMENTS, 
 column_N DATATYPE ARGUMENTS
);

Here is an example on how to use it这是有关如何使用它的示例

DECLARE @WeekDays 
TABLE(
  WeekNumber INT NOT NULL,
  ShortWeekDayName VARCHAR(40) NOT NULL, 
  WeekDayName VARCHAR(40) NOT NULL
);
 
INSERT INTO @WeekDays
VALUES 
(1,'Mon','Monday')  ,
(2,'Tue','Tuesday') ,
(3,'Wed','Wednesday') ,
(4,'Thu','Thursday'),
(5,'Fri','Friday'),
(6,'Sat','Saturday'),
(7,'Sun','Sunday'); 

SELECT * FROM @WeekDays;

https://dev.mysql.com/doc/refman/8.0/en/create-view.html says: https://dev.mysql.com/doc/refman/8.0/en/create-view.html说:

The definition cannot refer to a TEMPORARY table, and you cannot create a TEMPORARY view.该定义不能引用 TEMPORARY 表,并且您不能创建 TEMPORARY 视图。

Confirmed with a quick test:通过快速测试确认:

mysql> create temporary table foo ( i int );
Query OK, 0 rows affected (0.00 sec)

mysql> create view v as select * from foo;
ERROR 1352 (HY000): View's SELECT refers to a temporary table 'foo'

It makes sense if you think about it.如果您考虑一下,这是有道理的。 A view should be usable by other sessions.视图应该可供其他会话使用。 But a temporary table is limited to the current session where it is created.但是临时表仅限于创建它的当前 session。 So if you create a view that refers to a table only you can query in your session, it's irrelevant to other sessions and can only return an error.因此,如果您创建一个仅引用表的视图,您可以在 session 中查询,它与其他会话无关,只能返回错误。

This is why the statement in the documentation also mentions that you can't create a "temporary view."这就是为什么文档中的声明还提到您不能创建“临时视图”。 They are anticipating that you might want a view that is also scoped to your session, that can view tables scoped to your session.他们预计您可能想要一个也适用于您的 session 的视图,该视图可以查看适用于您的 session 的表。 But there is no such feature supported by MySQL.但 MySQL 不支持此类功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM