我有以下MySQL查询:
SELECT
s.student_socialnr, s.student_lastname, s.student_firstname,
cs.city_name,
scp.cpl_startdate, scp.cpl_enddate, scp.cpl_invoice,
cu.customer_name, scp.cpl_coursename
FROM students s
INNER JOIN studentcourseplan scp ON scp.student_id = s.student_id
INNER JOIN cityselections cs ON cs.city_id = s.student_city_id
INNER JOIN customers cu ON cu.customer_id = s.student_customer_id
这将输出如下内容:
+------------------+------------------+------------------+-----------+---------------+--------------+-------------+---------------+----------------+
| student_socialnr | student_lastname | student_firstname| city_name | cpl_startdate | cpl_enddate | cpl_invoice | customer_name | cpl_coursename |
+------------------+------------------+------------------+-----------+---------------+--------------+-------------+---------------+----------------+
| 000000-0000 | Doe | John | Dallas | 2012-06-01 | 2012-06-30 | 1337 | The customer | The course |
+------------------+------------------+------------------+-----------+---------------+--------------+-------------+---------------+----------------+
| 000000-0000 | Johnsson | Derp | Texas | 2012-02-01 | 2012-07-28 | 5000 | The customer | The course |
+------------------+------------------+------------------+-----------+---------------+--------------+-------------+---------------+----------------+
| 000000-0000 | Derpina | Lisa | New York | 2013-01-01 | 2013-04-01 | 2001 | The customer | The course |
+------------------+------------------+------------------+-----------+---------------+--------------+-------------+---------------+----------------+
我有问题。我希望能够在字段cpl_startdate
和cpl_enddate
上设置过滤器。因此,如果用户例如设置过滤器cpl_startdate = '2012-01-01'
和cpl_enddate = '2012-12-31'
,则应输出具有该范围之间的日期的所有行。因此,使用上面的示例,它应该只输出前两行,因为它们位于选定的日期范围内。
我试过
.. WHERE scp.cpl_startdate <= '2012-01-01' AND scp.cpl_enddate >= '2012-12-31'
..没有运气。我能以某种方式使用MySQL语法BETWEEN
吗?
另外,是否可以计算两个日期范围之间的天数?我想输出跨度之间的天数的INT。不一定在同一个查询..
答案 0 :(得分:2)
切换比较标志:
.. WHERE scp.cpl_startdate >= '2012-01-01' AND scp.cpl_enddate <= '2012-12-31'
要计算给定行的开始日期和结束日期之间的天数,请将其添加到您的select语句中:
DATEDIFF(scp.cpl_enddate, scp.cpl_startdate) AS DaysDifference
DATEDIFF(expr1,expr2)返回expr1 - expr2的日期差异。请参阅MySQL documentation中的更多内容。