在没有DATE字段的SQL中选择日期范围

时间:2014-04-03 11:47:07

标签: mysql date-parsing

我有一个包含year字段和week_number字段的MySQL数据库。这些只是INT字段。我希望能够执行查询以根据周数和年份在包含范围的日期之间进行选择,例如:

SELECT * FROM table WHERE year BETWEEN 2000 AND 2002 AND week_number BETWEEN 50 AND 10

但显然这会失败,因为查询中没有日期和时间的概念。我可以将这个特定的例子分成三个单独的查询,只需对输入数据进行一些解析:

SELECT * FROM table WHERE year = 2000 AND week_number >= 50
SELECT * FROM table WHERE year = 2001
SELECT * FROM table WHERE year = 2002 AND week_number <= 10

但是我想知道是否有更有效的方法来实现它?

修改

我想我可能不清楚实际问题。我希望能够以一种方式查询,即我可以在起始年/周组合和结束年/周组合之间获得所有日期。也就是说,在我上面的查询中,我希望返回以下行:

Year  Week Number
2000  50
2000  51
2000  52
2001   1
2001   2

(...and so on for all weeks in 2001...)

2001  51
2001  52
2002   1
2002   2

(...and so on for weeks 3-8...)

2002   9
2002  10

5 个答案:

答案 0 :(得分:1)

DROP TABLE my_table;

CREATE TABLE my_table (val1 INT NOT NULL, val2 INT NOT NULL,PRIMARY KEY(val1,val2));

INSERT INTO my_table VALUES (2013,48),(2013,49),(2013,50),(2013,51),(2013,52),(2014,1),(2014,2),(2014,3),(2014,5);

SELECT * FROM my_table WHERE (val1,val2) >= (2013,50) AND (val1,val2) <= (2014,3);
+------+------+
| val1 | val2 |
+------+------+
| 2013 |   50 |
| 2013 |   51 |
| 2013 |   52 |
| 2014 |    1 |
| 2014 |    2 |
| 2014 |    3 |
+------+------+

答案 1 :(得分:0)

如果你需要添加这3个查询结果,意味着选择2000弱50和2002之间的弱10使用OR

SELECT * FROM table WHERE (year = 2000 AND week_number >= 50) OR year = 2001 OR (year = 2002 AND week_number <= 10)

答案 2 :(得分:0)

这是你想要的吗?

SELECT * FROM table WHERE (year = 2000 AND week_number >= 50)
OR (year = 2001)
OR ( year = 2002 AND week_number <= 10)

答案 3 :(得分:0)

SELECT * FROM table WHERE
CONCAT(year,week_number) BETWEEN CONCAT(YEAR(MY_DATE_START),WEEKOFYEAR(MY_DATE_START))
    AND CONCAT(YEAR(MY_DATE_END),WEEKOFYEAR(MY_DATE_END))

MY_DATE_START MY_DATE_END 替换为您的日期。

<强>更新

在第二个想法中,您可能需要在所有周内使用零填充左键并将所有字符串强制转换为整数,因此查询变为:

SELECT *
FROM table
WHERE CAST( CONCAT(year,LPAD(week_number,2,"0")) AS UNSIGNED )
    BETWEEN CAST( CONCAT(YEAR(MY_DATE_START),LPAD(WEEKOFYEAR(MY_DATE_START),2,"0")) AS UNSIGNED )
    AND CAST( CONCAT(YEAR(MY_DATE_END),LPAD(WEEKOFYEAR(MY_DATE_END),2,"0")) AS UNSIGNED )

答案 4 :(得分:0)

你可以这样做:

SELECT 
   *
FROM table
WHERE DATE_ADD(MAKEDATE(year, 1), INTERVAL week_number WEEK) BETWEEN 
DATE_ADD(MAKEDATE(2000, 1), INTERVAL 50 WEEK) AND 
DATE_ADD(MAKEDATE(2002, 1), INTERVAL 10 WEEK)