我有这些params,但它没有返回所需的东西:
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'
有三个出发日期字段,我试图只返回日期落在两个日期之间的条目。我所拥有的就是归还一切。有没有更好的方法可以实现这一点?
答案 0 :(得分:4)
使用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_between CAST
/ CONVERT
- http://dev.mysql.com/doc/refman/5.0/en/cast-functions.html#function_convert 注意:如果这是您将要做很多事情的类型,请考虑使用BIGINT
字段类型而不是Date
将日期存储为UNIX时间戳。这样,您就不必使用CAST
进行BETWEEN
次比较。您可以使用FROM_UNIXTIME
(docs)格式化数据库,而不是每次比较时都进行转换。参见:
strtotime
- http://php.net/manual/en/function.strtotime.php date
- http://php.net/manual/en/function.date.php FROM_UNIXTIME
- http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_from-unixtime 答案 1 :(得分:3)
使用正确的括号:
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'))
答案 2 :(得分:0)
有很多方法可以让这个更清洁,但我一直保持着它,以显示上述查询的问题。
您需要在出发日期集之间建立链接,上面的日期过于宽泛。
WHERE(Profiles
。Departure1
&gt; ='2012-04-01'AND Profiles
。Departure1
&lt; ='2012-04-04')
要么
(Profiles
。Departure2
&gt; ='2012-04-01'和Profiles
。Departure2
&lt; ='2012-04-04')
要么
(Profiles
。Departure3
&gt; ='2012-04-01'和Profiles
。Departure3
&lt; ='2012-04-04')