简体   繁体   English

Mysql VIEW 具有显式列数据类型?

[英]Mysql VIEW with explicit column datatype?

How can I set the datatype of columns in a mysql view ?如何在mysql view中设置列的数据类型?

The following is incorrect:以下是不正确的:

CREATE VIEW person_view AS
SELECT 'Test' AS VARCHAR(20) person_firstname,
       person.age AS int(2) person_age
FROM person;

table person:表人:

#firstname, lastname, age
john, doe, 8
jane, doe, 5

The example data will trigger the generation of VARCHAR(4) for firstname and int(1) for age.示例数据将触发生成VARCHAR(4) for firstname 和int(1) for age。 But in fact I want to support VARCHAR(20) and int(2) for those columns in the view.但实际上我想为视图中的那些列支持VARCHAR(20)int(2)

Try using CAST or CONVERT尝试使用 CAST 或 CONVERT

CREATE VIEW myview AS SELECT CAST('Test' AS VARCHAR(20)) Column1 FROM mysource;

A view just sits on top of the underlying table against which it was defined, so views normally do not allow us to change the table definition.视图只是位于定义它的基础表之上,因此视图通常不允许我们更改表定义。 If, for example, you wanted to create a view which consisted only of the first 20 characters of some potentially larger varchar column, you could do so using LEFT , eg例如,如果您想创建一个仅包含某些可能较大的varchar列的前 20 个字符的视图,则可以使用LEFT来执行此操作,例如

CREATE VIEW yourView AS (
    SELECT LEFT(some_col, 20) AS some_col_short
    FROM mysource
)

But even here, we are not changing the definition of the table, only the way the underlying data is being viewed.但即使在这里,我们也没有改变表的定义,只是改变了基础数据的查看方式。

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

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