您可以重组表以使用 Unix 时间戳或 MySQL date,并使用比较器进行选择。或者您可以创建临时表并执行相同的操作。
您前进的方向对于维护和调试来说将是非常重要的。此外,正确的查询将比我相信的更复杂。例如,跨越年份将与上述一致。虽然许多线路都按照您的方式进行。
编辑:为了保持您当前的逻辑,SQL Select 语句必须是一系列WHEREs。例如:
SELECT * FROM table
WHERE
(month IN ('April', 'May') AND year = 2014)
将选择 2014 年的 4 月和 5 月。
以下将跨越一年:
SELECT * FROM table
WHERE
(month IN ('December') AND year = 2013)
OR
(month IN ('January') AND year = 2014)
从程序化的角度来看,您需要生成一系列年份和月份,包括您希望从中选择的一年中的所有月份。
这样一个数组的结构如下所示:
// For the first example
$where1 = array(
2014 => array(
'April',
'May'
)
);
// For the second example
$where2 = array(
2013 => array(
'December'
),
2014 => array(
'January'
)
);
您必须从这些数组中创建一个WHERE 子句。如:
/**
* Outputs
* [where1] (month IN ('April', 'May') AND year = 2014)
*
* [where2] (month IN ('December') AND year = 2013) OR (month IN ('January') AND year = 2014)
*/
foreach(array('where1','where1') as $where_name) {
$clause = '';
$where = $$where_name;
$wheres = array();
foreach($where as $year => $months) {
$wheres[] = "month IN ('" . implode("', '", $months) . "') AND year = $year";
}
$clause = '('.implode (') OR (', $wheres).')';
echo "[$where_name] $clause\n\n";
}
这应该可以解决问题。有一个工作示例here。收集月份列表几乎和你一直在做的一样,但更像是这样:
list($month, $year) = explode(" ", date('F Y', strtotime('-3 month')));
var_dump($month); // February
var_dump($year); // 2014
$array[$year][] = $month; // Will create the array structure as above
有更有效的方法,但这是一般的想法。我相信我给你留下了一些有趣的工具来解决你的问题。
要使其达到一个范围,您需要执行以下操作:
$where3 = array();
for ($prev_months = 1; $prev_months <= 5; $prev_months++) {
list($month, $year) = explode(" ", date('F Y', strtotime("-$prev_months month")));
$where3[$year][] = $month;
}
您可以在此处查看工作示例:
http://ideone.com/UWI5wI
作为参考,以下是使用您的方法与公认规范的示例:
// your last and 5
(month IN ('April', 'March', 'February', 'January') AND year = 2014) OR (month IN ('December') AND year = 2013)
// native 1 and 5
date <= 2014-05-01 01:00:00 AND date > 2013-12-01 01:00:00
我使用第一个(这不是惯例),因为每个月都有一个第一个。您可能希望使用目标月份的最后一天,而不是下个月的第一天,但您明白了。
当跨越很长一段时间时,差异会更加明显:
// 2 years, yours
(month IN ('April', 'March', 'February', 'January') AND year = 2014) OR (month IN ('December', 'November', 'October', 'September', 'August', 'July', 'June', 'May', 'April', 'March', 'February', 'January') AND year = 2013) OR (month IN ('December', 'November', 'October', 'September', 'August', 'July', 'June', 'May') AND year = 2012)
// The conventional way is still just two comparators...