[英]MySQL select all rows from this year to a specific month from last year
I'm creating a system for a school that needs to retrieve data from April of this year to June from last year. 我正在为一所学校创建一个系统,该系统需要检索从今年4月到去年6月的数据。
I needed a query that can retrieve from this dates due to their school year always starts from June and end in April. 我需要一个可以从该日期检索的查询,因为他们的学年总是从6月开始到4月结束。
I tried selecting dates using Where clause. 我尝试使用Where子句选择日期。
"SELECT * FROM students WHERE year(c_date) = ? AND month(c_date) = ? AND c_occupation = 'Student'"
the question marks are use for java language which to prepare a statement using this code 问号用于Java语言,该Java语言使用此代码准备语句
pst=conn.prepareStatement(Sql);
pst.setInt(1, year);
pst.setInt(2, month);
I also tried this method but with this, I need to enter the date again after a year has pass. 我也尝试过这种方法,但是,经过一年,我需要再次输入日期。
SELECT users.* FROM users
WHERE dateadded <= '2019-06-01'
AND dateadded >= '2018-4-30'
I wanted it to automatically based on what today's year is. 我希望它能够根据当年的情况自动生成。
So for example today is March 20, 2019. I should be able to return all the values from this day until June 1, 2018 举例来说,今天是2019年3月20日。我应该能够返回从这一天到2018年6月1日的所有值。
Your code can be : 您的代码可以是:
LocalDate from = LocalDate.now().minusYears(1); // 2018-04-29
LocalDate to = LocalDate.of(Year.now().getValue(), Month.JUNE, 1); // 2019-06-01
String sql = "SELECT * FROM students WHERE dateadded BETWEEN ? AND ? AND c_occupation = 'Student'";
pst = conn.prepareStatement(Sql);
pst.setObject(1, from);
pst.setObject(2, to);
LocalDate.now().minusYears(1);
return the same day of last year 返回去年的同一天 LocalDate.of(Year.now().getValue(), Month.JUNE, 1);
return the 1st June of the current year 返回当年的6月1日 dateadded BETWEEN ? AND ?
will select all between the from
and to
dates 将在from
和to
日期之间选择所有内容 pst.setObject(1, from);
if you are using JDBC 4+ you can set a LocalDate
like so 如果您使用的是JDBC 4+,则可以像这样设置LocalDate
Some references : 一些参考:
Your last method can be made to work using this approach 您可以使用此方法使最后一种方法起作用
SELECT * FROM students
WHERE dateadded BETWEEN (CONCAT(YEAR(NOW()), '-06-01') - INTERVAL 1 YEAR) AND CURDATE()
AND c_occupation = 'Student';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.