我在MySQL表中有以下列,即YYYYMMDD
:
launch_month
2018-06-01
2018-07-01
2018-08-01
我想使用'201806'
字符串在旁边创建一个新列,因此使用上面的新列看起来像:
launch_id
201806
201807
201808
您可以使用字符串函数,如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 |
我将使用基于launch_month(date)和date_format生成的列,如@forpas所述。
ALTER TABLE launches
ADD launch_id INT AS (DATE_FORMAT(launch_month, '%Y%m')) STORED;
参见演示:)
可以安全地将此格式重新键入为int
。
对于仅选择,可以使用虚拟
列(而不是存储
)。 然后在每次选择时计算launch_id,但不会将数据存储两次。
对于索引,您需要将列存储
。