我需要在两个表里查询数据,执行这条SQL 是用一个定时任务来执行,而我的这个SQL的条件就是当前时间到当前时间的前一天之内的这段时间(假如现在是2012.12.12的上午10点,那么时间范围就是2012.12.11号的上午10点到12号的上午10点这段时间,为条件来查询这短时间内的数据)求解怎么写这段SQL!!!!!第一个问题是:你的定时任务是靠程序来定时执行的 还是 靠数据库的JOB来定时执行的?
——这关系到时间应该在哪边进行处理。
第二个问题是:什么数据库?
——不同数据库关于时间的处理函数是不同的。
+1
我上面写的只是一个在sql里面操作这个时间的方法使用oracle数据库 不同的数据库函数也不一样
同样不同的层次执行操作方式也不一样!DB2的SQL,例如去表LDUSER中的数据,该表中有日期makedate和时间maketime的字段
用Calendar
select * from lduser where (makedate =(select current_date - 1 day from dual) and maketime >=(select current_time from dual ) ) or (makedate =(select current_date from dual ) and maketime <(select current_time from dual))
public static void main(String[] args) {有两种方法一个是用程序来获取条件时间,一个是用sql自带的时间函数来做条件。不过建议用第一种。
Calendar c = Calendar.getInstance();
long l = c.getTimeInMillis();
long res = l - 24 * 3600 * 1000;
c.setTimeInMillis(res);
String s = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(res);
String st = "2012-12-02 12:12:20";//要传的参数
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date d = null;
try {
d = sf.parse(st);
} catch (ParseException e) {
e.printStackTrace();
}
long t = d.getTime();
long p = t - 24 * 3600 * 1000;
String test = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(p);
System.out.println(test);
}
Calendar c=Calendar.getInstance();
Date currentDate=c.getTime();//当前系统时间
c.add(Calendar.DAY_OF_YEAR,-1);//当前时间减去一天即昨天的这个时间
Date yesterDay=c.getTime();//获取昨天
//currentDate和yesterDay就是你要的时间条件了
--如果你的时间字段为字符串类型
WHERE T.TIME BETWEEN TO_CHAR(SYSDATE-1,'YYYY-MM-DD HH24:MI:SS') AND TO_CHAR(SYSDATE,'YYYY-MM-DD HH24:MI:SS')
--如果你的时间字段为data类型
WHERE T.TIME BETWEEN SYSDATE-1 AND SYSDATE