SQLite,SELECT和max函数

时间:2015-02-05 13:53:10

标签: c++ sqlite

为什么以下代码在使用max函数时会给出不同的结果?我认为在这种情况下它应该返回SQLITE_DONE

#include <boost/scope_exit.hpp>

#include <sqlite3.h>

#include <cstdlib>
#include <iostream>

int main()
{
  sqlite3* db;
  int rc = sqlite3_open(":memory:", &db);
  BOOST_SCOPE_EXIT_ALL(&db)
  {
    sqlite3_close(db);
  };
  if (rc != SQLITE_OK)
  {
    std::cerr << "Can't open database."
      << " Error code: " << rc
      << " Error description: " << sqlite3_errmsg(db);
    return EXIT_FAILURE;
  }

  char* errMsg;
  rc = sqlite3_exec(db, "CREATE TABLE foo (bar INTEGER)", NULL, NULL, &errMsg);
  if (rc != SQLITE_OK)
  {
    std::cerr << "Can't create \"foo\" table."
      << " Error code: " << rc
      << " Error description: " << errMsg;
    sqlite3_free(errMsg);
    return EXIT_FAILURE;
  }

  {
    sqlite3_stmt* stmt;
    rc = sqlite3_prepare_v2(db, "SELECT bar FROM foo WHERE bar = 1", -1, &stmt, NULL);
    if (rc != SQLITE_OK)
    {
      std::cerr << "Can't prepare SELECT statement."
        << " Error code: " << rc
        << " Error description: " << sqlite3_errmsg(db);
      return EXIT_FAILURE;
    }
    BOOST_SCOPE_EXIT_ALL(&stmt)
    {
      sqlite3_finalize(stmt);
    };

    rc = sqlite3_step(stmt);
    std::cout << rc << std::endl; // 101 -- SQLITE_DONE
  }

  {
    sqlite3_stmt* stmt;
    rc = sqlite3_prepare_v2(db, "SELECT max(bar) FROM foo WHERE bar = 1", -1, &stmt, NULL);
    if (rc != SQLITE_OK)
    {
      std::cerr << "Can't prepare SELECT statement."
        << " Error code: " << rc
        << " Error description: " << sqlite3_errmsg(db);
      return EXIT_FAILURE;
    }
    BOOST_SCOPE_EXIT_ALL(&stmt)
    {
      sqlite3_finalize(stmt);
    };

    rc = sqlite3_step(stmt);
    std::cout << rc << std::endl; // 100 -- SQLITE_ROW
  }
}

提前致谢。

1 个答案:

答案 0 :(得分:0)

当您使用GROUP BY时,您会为分组列的每个唯一值获得一个组。 如果不存在要分组的任何行,则没有组,并且查询不返回任何行。

当您使用像max()这样没有GROUP BY的聚合函数时,整个表将成为一个组。 即使表是空的,也会发生这种情况,即,然后您获得一个聚合空集的单个组。

如果您不想在没有bar = 1行的情况下获得结果,请添加GROUP BY bar