SQLite ORDER BY嵌套查询的结果

时间:2012-08-18 12:01:24

标签: android sqlite sql-order-by nested-query

我有一个包含多个日期字段的表,我想选择日期最接近当前日期的行,而不管它是哪一列。

数据库中有2个表; 涵盖:

create table covers (_id integer primary key autoincrement, "
        + "stallionName integer not null, mareName integer not null, firstCoverDate text not null, lastCoverDate text not null, "
        + "scan14Date text not null, scan28Date text not null, foalingDate text not null, inFoal integer not null, notes text not null," +
        "FOREIGN KEY (stallionName) REFERENCES horses (_id), FOREIGN KEY (mareName) REFERENCES horses (_id))

stallionName和mareName是引用马表中相关马的行_id的整数(因此,SQL查询有多个连接来获取种马和母马的名称,而不仅仅是行_id)。所有日期列的格式均为“YYYY-MM-DD”

和马:

create table horses (_id integer primary key autoincrement, "
        + "name text not null, type integer not null, birthDate text not null, vaccineDate text not null, "
        + "inFoal integer not null, notes text not null)

type是一个引用微调器位置的整数(类型是母马,种马,阉割等)

我想从封面表中选择5行,其值为scan14Date,scan28Date和foalingDate,它们最接近今天的日期(即5个最紧急的行)

到目前为止,这是我的努力;

SELECT covers.* horses1.name AS stallionNameText, horses2.name AS mareNameText
FROM horses horses1 JOIN covers ON horses1._id = covers.stallionName JOIN horses     horses2 ON horses2._id = covers.MareName
WHERE covers._id IN

(SELECT DISTINCT _id FROM

(SELECT covers.scan14Date AS date, covers._id
FROM covers
WHERE date > dateToday
UNION

SELECT covers.scan28Date AS date, covers._id
FROM covers
WHERE date > dateToday

UNION

SELECT covers.foalingDate AS date, covers._id
FROM covers
WHERE date > dateToday

ORDER BY date)
LIMIT 5)

(可以假设'dateToday'的形式也是YYYY-MM-DD。它在java中整理出来)

现在,下面的嵌套查询成功选择了5'最紧急的'row _ids;

(SELECT DISTINCT _id FROM

(SELECT covers.scan14Date AS date, covers._id
FROM covers
WHERE date > dateToday
UNION

SELECT covers.scan28Date AS date, covers._id
FROM covers
WHERE date > dateToday

UNION

SELECT covers.foalingDate AS date, covers._id
FROM covers
WHERE date > dateToday

ORDER BY date)
LIMIT 5)

第一部分成功获取上面选择的行_id的所有数据;

SELECT covers.* horses1.name AS stallionNameText, horses2.name AS mareNameText
FROM horses horses1 JOIN covers ON horses1._id = covers.stallionName JOIN horses     horses2 ON horses2._id = covers.MareName
WHERE covers._id IN
....

我遇到的问题是嵌套查询返回的行_ids的顺序在整个查询中丢失了。例如,如果嵌套查询返回行_ids(6,3,4,12,15),则整个查询将按顺序显示它(3,4,6,12,15)

然后我想返回种马名称,母马名称,lastCoverDate,14ScanDate,28ScanDate和foalingDate。

我的问题是如何维护内部查询返回的顺序?我天真地尝试在最后添加ORDER BY日期,但可以预见的是没有这样的列。

谢谢你花时间阅读。

(另外,我确信我的SQL查询不是最有效的方法,但我对这一切都很新)

1 个答案:

答案 0 :(得分:0)

在内部查询的结果中包含日期,然后您可以在外部查询中按日期排序。您的Java包装器可以简单地忽略结果中的日期字段。