我还是SQLite的新手,也是更具体的SQL,所以请放轻松。我的SQLite数据库中有三个表,如下所示:
TableA
DateAdded Data1 Data2
1/1/2012 a b
1/3/2012 c d
1/2/2012 e f
TableB
DateAdded Data3 Data4
1/6/2012 g h
1/5/2012 i j
1/4/2012 k l
TableC
DateAdded Data5 Data6
1/8/2012 m n
1/9/2012 o p
1/7/2012 q r
每个表都有DateAdded
列,这是datetime
数据类型。我想获得所有三个表的最新datetime
值。
现在我一次做一张桌子并比较结果:
private DateTime GetEndTime()
{
DateTime retVal = new DateTime();
DateTime sa = new DateTime();
DateTime gps = new DateTime();
SQLiteCommand cmd = mySQL.CreateCMD();
SQLiteDataReader dbReader = mySQL.ExecuteQuerySQL("SELECT DateAdded FROM DF ORDER BY ROWID DESC LIMIT 1", cmd);
if (dbReader.HasRows)
{
dbReader.Read();
retVal = dbReader.GetDateTime(0);
}
dbReader.Close();
dbReader = mySQL.ExecuteQuerySQL("SELECT DateAdded FROM SA ORDER BY ROWID DESC LIMIT 1", cmd);
if (dbReader.HasRows)
{
dbReader.Read();
sa = dbReader.GetDateTime(0);
}
dbReader.Close();
if (retVal < sa)
retVal = sa;
dbReader = mySQL.ExecuteQuerySQL("SELECT DateAdded FROM GPS ORDER BY ROWID DESC LIMIT 1", cmd);
if (dbReader.HasRows)
{
dbReader.Read();
gps = dbReader.GetDateTime(0);
}
dbReader.Close();
mySQL.disposeCMD(cmd);
if (retVal < gps)
retVal = gps;
return retVal;
}
我知道必须有更好的方法。有什么建议吗?
答案 0 :(得分:3)
您可以从每个表中选择Max DateAdded,然后将这些行合并并选择最大值,如下所示:
select MAX(MaxDateAdded) from
(
select MAX(DateAdded) as MaxDateAdded from a
union
select MAX(DateAdded) as MaxDateAdded from b
union
select MAX(DateAdded) as MaxDateAdded from c
) AS UnionedDateAddedTables
答案 1 :(得分:2)
SELECT MAX(DateAdded)
FROM
(
SELECT MAX(DateAdded) AS DateAdded FROM tableA
UNION
SELECT MAX(DateAdded) AS DateAdded FROM tableb
UNION
SELECT MAX(DateAdded) AS DateAdded FROM tablec
)
修改强>:
我正在替换:
Instead of selecting all rows
使用
SELECT MAX(DateAdded) AS DateAdded FROm table
感谢@dugas