0

我有以下 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_startdatecpl_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'

..没有运气。我可以BETWEEN以某种方式使用 MySQL 语法吗?

另外,是否可以计算两个日期范围之间的天数?我想输出一个跨度之间天数的 INT。不一定在同一个查询中..

4

1 回答 1

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文档中查看更多信息。

于 2012-06-16T10:57:45.947 回答