使用SQLiteCommand使用子查询的最佳方法是什么?

时间:2016-12-18 16:30:19

标签: c# sql sqlite database-connection

我现在的代码如下:

using (dbConnection)
{
    if (dbConnection.State != System.Data.ConnectionState.Open) dbConnection.Open();

    SQLiteCommand command = new SQLiteCommand("SELECT * FROM BoardStates WHERE Move = @subquery", dbConnection);
    SQLiteCommand cmd = new SQLiteCommand("SELECT MAX(Move) FROM BoardStates", dbConnection);
    command.Parameters.AddWithValue("@subquery", cmd.ExecuteScalar().ToString());

    SQLiteDataReader reader = command.ExecuteReader();
    while (reader.Read())
    {
        Console.WriteLine("Game: " + reader["Game"] + "\tMove: " + reader["Move"] + "\tState: " + reader["State"]);
    }
}

我想要返回最后一步的行。我通过使用2个单独的SQLiteCommands来做到这一点。有没有办法优化它或将它组合成1个SQLiteCommand?

1 个答案:

答案 0 :(得分:0)

documentation说:

  

括在括号中的SELECT语句可能显示为标量。用作标量的SELECT必须返回带有单个列的结果集。表达式的结果是SELECT语句返回的第一行中唯一列的值。

SELECT *
FROM BoardStates
WHERE Move = (SELECT MAX(Move)
              FROM BoardStates);

但要获得具有最大值的行,您只需使用排序:

SELECT *
FROM BoardStates
ORDER BY Move DESC
LIMIT 1;