Mysql View:在使用 if 语句创建 VIEW 时提供用户定义的数据类型时出现问题

问题描述 投票:0回答:1
 desc user_roles;
+------------+------------+------+-----+-------------------+-----------------------------+
| Field      | Type       | Null | Key | Default           | Extra                       |
+------------+------------+------+-----+-------------------+-----------------------------+
| id         | int(50)    | NO   | PRI | NULL              | auto_increment              |
| user_id    | int(50)    | NO   | MUL | NULL              |                             |
| role_id    | int(50)    | NO   |     | NULL              |                             |
| created_at | timestamp  | NO   |     | CURRENT_TIMESTAMP |                             |
| updated_at | timestamp  | NO   |     | CURRENT_TIMESTAMP | on update CURRENT_TIMESTAMP |
| status     | tinyint(3) | YES  |     | 1                 |                             |

create or replace view bff_user_roles as select user_roles.id as id,  
user_id as user_id, role_id as role_id, updated_at as updated_at, status as status,
IF(created_at ='0000-00-00 00:00:00', "1990-01-01 23:59:59", created_at)
 as created_at as timestamp from user_roles;

desc bff_user_roles;
+------------+-------------+------+-----+---------------------+-------+
| Field      | Type        | Null | Key | Default             | Extra |
+------------+-------------+------+-----+---------------------+-------+
| id         | int(50)     | NO   |     | 0                   |       |
| user_id    | int(50)     | NO   |     | NULL                |       |
| role_id    | int(50)     | NO   |     | NULL                |       |
| updated_at | timestamp   | NO   |     | 0000-00-00 00:00:00 |       |
| status     | tinyint(3)  | YES  |     | 1                   |       |
| created_at | varchar(19) | NO   |     |                     |       |
+------------+-------------+------+-----+---------------------+-------+

问题在于,当我在 MySql 数据库中创建 VIEW 时,它会将created_at 列数据类型视为 varchar 。但它应该是并且需要时间戳。我尝试显式添加数据类型,但它不起作用。由于 user_roles 表中存在一些遗留数据问题,我在 VIEW 中采用了 if 语句。

mysql view sql-view
1个回答
0
投票

IF(created_at ='0000-00-00 00:00:00', "1990-01-01 23:59:59", created_at)
处理 2 个替代值。其中之一 (
created_at
) 是 TIMESTAMP,另一个 (
"1990-01-01 23:59:59"
) 是 VARCHAR(19)。服务器从这两种格式中选择最常见的格式,它是 VARCHAR(19)。

您不能使用字符串文字,而是使用日期时间文字

IF(created_at ='0000-00-00 00:00:00', TIMESTAMP '1990-01-01 23:59:59', created_at)

在这种情况下,最常见的数据类型是 DATETIME。

© www.soinside.com 2019 - 2024. All rights reserved.