MySQL,拆分列数据并通过拆分数据获取结果

时间:2014-11-26 05:36:05

标签: mysql sql date select between

我有一个MySQL表数据,如下所示

+--------------------------+
| period                   |
+--------------------------+
| 2014-11-27 to 2014-11-28 |
| 2014-11-09 to 2014-11-09 |
| 2014-11-07 to 2014-11-07 |
| 2014-11-06 to 2014-11-06 |
| 2014-11-04 to 2014-11-04 |
| 2014-11-02 to 2014-11-02 |
| 2014-11-01 to 2014-11-02 |
| 2014-10-24 to 2014-10-24 |
| 2014-10-23 to 2014-10-24 |
| 2014-10-23 to 2014-10-24 |
| 2014-10-23 to 2014-10-23 |
| 2014-10-23 to 2014-10-23 |
| 2014-10-20 to 2014-10-20 |
| 2014-10-18 to 2014-10-18 |
| 2014-10-17 to 2014-10-17 |
| 2014-10-13 to 2014-10-13 |
| 2014-10-13 to 2014-10-13 |
| 2014-10-09 to 2014-10-10 |
| 2014-10-06 to 2014-10-07 |
| 2014-10-01 to 2014-10-10 |
| 2014-09-30 to 2014-09-30 |
| 2014-09-24 to 2014-09-24 |
| 2014-09-12 to 2014-09-12 |
| 2014-09-12 to 2014-09-12 |
| 2014-09-08 to 2014-09-09 |
| 2014-09-08 to 2014-09-08 |
| 2014-09-08 to 2014-09-08 |
| 2014-09-01 to 2014-09-01 |
| 2014-09-01 to 2014-09-01 |
+--------------------------+

在这里,我想了解两个日期之间的详细信息,如(2014-09-01 to 2014-09-30) 或(2014-09-01 to 2014-010-3 0)或(2014-09-01 to 2014-11-30)并且它是 varchar 列,是否有可能在两个日期之间获得结果?

3 个答案:

答案 0 :(得分:1)

我认为以下是正确的,

select period  from mysql_common.leave_details 
where  (period like '%-11-%' or period like '%-10-%' or period like '%-09-%') 
order by period desc;

答案 1 :(得分:1)

首先,您应该对表进行规范化并使用mysql本机日期数据类型存储日期,并确保将它们存储在两列start_dateend_date中。这将使你的生活变得轻松。

现在回到当前的情况有一种方法可以做到,首先使用substring_index函数从varchar字符串中提取开始日期和结束日期,最后在使用having的条件下使用它们子句。

select 
str_to_date(substring_index(period,'to',1),'%Y-%m-%d') as start_date,   
str_to_date(substring_index(period,'to',-1),'%Y-%m-%d') as end_date,
period 
from table_name 
having start_date >='2014-09-01' and end_date <='2014-09-30';

答案 2 :(得分:0)

试试这个:

SELECT * 
FROM table1 A
WHERE DATE(LEFT(A.period, 10)) BETWEEN DATE('2014-09-01') AND DATE('2014-09-30') AND 
      DATE(RIGHT(A.period, 10)) BETWEEN DATE('2014-09-01') AND DATE('2014-09-30');