使用日期列在 MySQL 中将新列创建为年和月字符串



我在MySQL表中有YYYYMMDD的以下列:

launch_month    
2018-06-01  
2018-07-01      
2018-08-01  

我想使用'201806'字符串在此旁边创建一个新列,因此使用上面的新列将如下所示:

launch_id
201806  
201807  
201808

我会使用基于launch_month(日期(和date_format生成的列,如@forpas所述。

ALTER TABLE launches
ADD launch_id INT AS (DATE_FORMAT(launch_month, '%Y%m')) STORED;

查看演示:)

可以安全地将此格式重新键入为INT

对于仅选择,您可以使用VIRTUAL列(而不是STORED(。然后,每次选择都会计算launch_id,但不会存储数据两次。

对于索引,您需要STORED列。

您可以使用字符串函数,如replace()left()

select launch_month, 
left(replace(launch_month, '-', ''), 6) launch_id
from tablename

date_format()

select launch_month, 
date_format(launch_month, '%Y%m') launch_id
from tablename

请参阅演示。

结果:

| launch_month | month  |
| ------------ | ------ |
| 2018-06-01   | 201806 |
| 2018-07-01   | 201807 |
| 2018-08-01   | 201808 |

最新更新