1

我还是 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;
}

知道一定有更好的方法。有什么建议么?

4

2 回答 2

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
于 2012-10-01T18:28:38.363 回答
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

于 2012-10-01T18:27:01.880 回答