MySQL 查询将字符串转换为月份(数字)?

mysqlmysqli database

使用 str_to_date() 方法 −

select month(str_to_date(yourColumnName,'%b')) from yourTableName;

首先我们创建一个表 −

mysql> create table DemoTable
   (
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   MonthName varchar(100)
   );
Query OK, 0 rows affected (0.76 sec)

使用 insert 命令在表中插入一些记录 −

mysql> insert into DemoTable(MonthName) values('Jan');
Query OK, 1 row affected (0.25 sec)
mysql> insert into DemoTable(MonthName) values('Mar');
Query OK, 1 row affected (0.13 sec)
Display all records from the table using select statement:
mysql> select *from DemoTable;

输出

+----+-----------+
| Id | MonthName |
+----+-----------+
| 1  | Jan       |
| 2  | Mar       |
+----+-----------+
2 rows in set (0.00 sec)

以下是将字符串转换为月份(数字)的查询 −

mysql> select month(str_to_date(MonthName,'%b')) from DemoTable;

输出

+------------------------------------+
| month(str_to_date(MonthName,'%b')) |
+------------------------------------+
| 1                                  |
| 3                                  |
+------------------------------------+
2 rows in set (0.05 sec)

相关文章