我有一个包含多个日期字段的表,我想选择日期最接近当前日期的行,无论它是哪一列。
数据库中有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 个“最紧急”的行 _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 查询不会是最有效的方法,但我对这一切还很陌生)