从日期字符串中提取日期编号

时间:2010-05-08 07:25:42

标签: mysql converter weekday

是否可以从日期名称中提取整数值,即“Mon”,“Tue”,“Wed”和SQL语句?

例如:

 Mon = 1
 Tue = 2
 Wed = 3

4 个答案:

答案 0 :(得分:9)

尝试FIELD:

SELECT FIELD('Mon', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun');
    -> 1
SELECT FIELD('Thu', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun');
    -> 4

http://dev.mysql.com/doc/refman/5.4/en/string-functions.html#function_field

答案 1 :(得分:4)

如果你只有一个只有周一,周二,周三等的非日期时间字段,你可以使用STR_TO_DATE()WEEKDAY()函数来得到这样的结果:

SELECT WEEKDAY(STR_TO_DATE(CONCAT('201011 ', yourField), '%X%V %W')) + 1 AS WeekIndex;

测试用例:

SELECT WEEKDAY(STR_TO_DATE(CONCAT('201011 ', 'Mon'), '%X%V %W')) + 1 AS WeekIndex;
+-----------+
| WeekIndex |
+-----------+
|         1 |
+-----------+

SELECT WEEKDAY(STR_TO_DATE(CONCAT('201011 ', 'Tue'), '%X%V %W')) + 1 AS WeekIndex;
+-----------+
| WeekIndex |
+-----------+
|         2 |
+-----------+

SELECT WEEKDAY(STR_TO_DATE(CONCAT('201011 ', 'Wed'), '%X%V %W')) + 1 AS WeekIndex;
+-----------+
| WeekIndex |
+-----------+
|         3 |
+-----------+

SELECT WEEKDAY(STR_TO_DATE(CONCAT('201011 ', 'Thu'), '%X%V %W')) + 1 AS WeekIndex;
+-----------+
| WeekIndex |
+-----------+
|         4 |
+-----------+

答案 2 :(得分:1)

如果您的字段是日期字段,请使用

SELECT DATE_FORMAT(my.field, "%w");

有关MySQL的更多信息可以选择DATE_FORMAT here

答案 3 :(得分:1)