简体   繁体   中英

Mysql VIEW with explicit column datatype?

How can I set the datatype of columns in a 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. But in fact I want to support VARCHAR(20) and int(2) for those columns in the view.

Try using CAST or 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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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