如何在两个日期时间列之间查询行?
我的示例表:
message | startdatetime | enddatetime
--------------------------------------------------------------------------------
Hi | 2013-04-09 10:00:00 | 2013-04-09 10:30:00
Good morning | 2013-04-09 10:40:00 | 2013-04-09 10:50:00
我的查询:
fromDateTime =“2013-04-09 10:00:00”; toDateTime =“2013-04-09 10:50:00”;
c1 = myDB.rawQuery("select * from masterdatatable where number=? and startdatetime >= datetime(?) and enddatetime <= datetime(?) order by enddatetime, new String[]{imei,fromDateTime,toDateTime});
此处如果传递fromDateTime="2013-04-09 10:00:00 " and toDateTime="2013-04-09 10:50:00 "
此查询正确地返回上述两个记录。
但是如果我传递fromDateTime="2013-04-09 10:05:00 "; toDateTime="2013-04-09 10:20:00 "
,则此查询返回空光标。实际上我希望这个查询返回第一行。怎么做到这一点?
答案 0 :(得分:1)
我是通过以下方法实现的,
Cursor c0 = myDB.rawQuery("select startdatetime from masterdatatable where datetime(?) >= startdatetime and datetime(?) <= enddatetime order by startdatetime asc limit 1", new String[]{fromDateTime,fromDateTime});
String fromDate1=fromDateTime;
if(c0.moveToFirst())
{
fromDate1 = c0.getString(0);
}
Log.i("date", "fromDate1->"+fromDate1);
Cursor c01 = myDB.rawQuery("select startdatetime from masterdatatable where datetime(?) >= startdatetime and datetime(?) <= enddatetime order by startdatetime desc limit 1", new String[]{toDateTime,toDateTime});
String fromDate2=toDateTime;
if(c01.moveToFirst())
{
fromDate2 = c01.getString(0);
}
Log.i("date", "fromDate2->"+fromDate2);
c1 = myDB.rawQuery("select * from masterdatatable where startdatetime between datetime(?) and datetime(?) order by enddatetime, new String[]{fromDate1,fromDate2});
答案 1 :(得分:0)
由于你的条件,它不会返回第一行..第一行的endTime不是
2013-04-09 10:30:00 doesn't
小于
toDateTime="2013-04-09 10:20:00
因为你没有得到第一行......
<强>更新强> 如果您仍想返回第一行,则可以创建新查询 这将检查startDate是否在给定输入之间..
答案 2 :(得分:0)
尝试使用以下SQL查询
select * from masterdatatable
where number=?
and fromdate between startdatetime and enddatetime
and todate between startdatetime and enddatetime
order by enddatetime