我有这些 where 参数,但它没有返回所需的内容:
WHERE `Profiles`.`Departure1` >= '2012-04-01'
OR `Profiles`.`Departure2` >= '2012-04-01'
OR `Profiles`.`Departure3` >= '2012-04-01'
AND `Profiles`.`Departure1` <= '2012-04-04'
OR `Profiles`.`Departure2` <= '2012-04-04'
OR `Profiles`.`Departure3` <= '2012-04-04'
有三个出发日期字段,我试图只返回日期介于两个日期之间的条目。我在这里拥有的是归还一切。有没有更好的方法可以真正起作用?
最佳答案
使用 mySQL 的 BETWEEN
运算符:
WHERE
`Profiles`.`Departure1` BETWEEN CAST('2012-04-01' AS Date) AND CAST('2012-04-04' AS Date) OR
`Profiles`.`Departure2` BETWEEN CAST('2012-04-01' AS Date) AND CAST('2012-04-04' AS Date) OR
`Profiles`.`Departure3` BETWEEN CAST('2012-04-01' AS Date) AND CAST('2012-04-04' AS Date)
查看文档:
BETWEEN
- http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#operator_betweenCAST
/CONVERT
- http://dev.mysql.com/doc/refman/5.0/en/cast-functions.html#function_convert
注意:如果这是您要经常做的事情,请考虑将您的日期存储为 UNIX 时间戳,使用 BIGINT
字段类型而不是 日期
。这样,您就不必过多地使用 CAST
来进行 BETWEEN
比较。您可以使用 FROM_UNIXTIME
( docs ) 在离开数据库的路上进行格式化,而不是每次比较时都在转换。见:
- PHP 的
strtotime
- http://php.net/manual/en/function.strtotime.php - PHP 的
日期
- http://php.net/manual/en/function.date.php - mySQL 的
FROM_UNIXTIME
- http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_from-unixtime
关于php - 更改 MySQL WHERE 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9996579/