在where子句中组合不同的语句

时间:2011-01-20 01:57:47

标签: mysql where-clause

我有一些where子句,如:

$sWhere = " WHERE MONTH(Inspection_datetime) = '".$Month."' AND 
            YEAR(Inspection_datetime) = '".$Year."' ";

和另一个命令:

WHERE DAY(Inspection_datetime) BETWEEN 8 AND 14
GROUP BY Line, WEEK(Inspection_datetime), YEAR(Inspection_datetime)

如何将两个命令组合成一个?因为我想在第二周显示数据并在选定的月份和年份中对它们进行排序。

3 个答案:

答案 0 :(得分:0)

只需在您的陈述中添加另一个AND子句。

" MONTH(Inpsection_datetime) = '".$Month."' AND YEAR(Inspection_datetime) = '".$Year."' AND WHERE DAY(Inspection_datetime) BETWEEN 8 AND 14 GROUP BY Line, WEEK(Inspection_datetime), YEAR(Inspection_datetime)";

答案 1 :(得分:0)

WHERE(cond1 AND cond2 AND cond3) ORDER by(column_to_sort_on)[desc]

我认为要对查询结果进行排序,您必须使用“order by ...”

问候, - M.S。

答案 2 :(得分:0)

在日期列上执行功能是一个好主意。除非桌子很小或者你并不真正关心性能,否则就是这样。反向总是更好 - 构建日期& /范围以进行测试。

YEAR(datecolumn) = X and MONTH(datecolumn) = Y
<< index cannot be used, MONTH() has to be run on all rows

条件变得(在MySQL上看起来更复杂)

$sWhere = " WHERE Inspection_datetime >= '".$Year.'-'.$Month."-1'
              AND Inspection_datetime <  '".$Year.'-'.$Month."-1'
                       + interval 1 month - interval 1 day"

要将其添加到其他条件,整个WHERE子句将是

$sWhere = " WHERE Inspection_datetime >= '".$Year.'-'.$Month."1'
              AND Inspection_datetime <  '".$Year.'-'.$Month."1'
                       + interval 1 month - interval 1 day
              AND DAY(Inspection_datetime) BETWEEN 8 AND 14"