我正在用 C 语言开发一个小型应用程序,我想使用 SQLite 对数据库执行一些查询。问题是我的行为很奇怪。
如果我在 Firefox 插件“SQLite Manager”上的同一个数据库上运行相同的查询,我会得到预期的结果,但是如果我通过程序中的 C 接口(interface)运行它,我会得到结果元组的错误顺序。
可以查到数据库here (CSV 或 SQLite 格式),而有问题的查询是这个:
SELECT name, slot, id, species_id
FROM type_names T, pokemon_types PT, pokemon P
WHERE T.type_id = PT.type_id
AND P.id = PT.pokemon_id AND T.local_language_id = 9
AND P.identifier LIKE '%char%'
ORDER BY P.species_id;
在 Firefox 上我得到了预期的结果:
+--------+------+-------+------------+ | name | slot | id | species_id | +--------+------+-------+------------+ | Fire | 1 | 4 | 4 | | Fire | 1 | 5 | 5 | | Fire | 1 | 6 | 6 | | Flying | 2 | 6 | 6 | | Fire | 1 | 10034 | 6 | | Dragon | 2 | 10034 | 6 | | Fire | 1 | 10035 | 6 | | Flying | 2 | 10035 | 6 | | Fire | 1 | 390 | 390 | +--------+------+-------+------------+
while in C I get this:
+--------+------+-------+------------+ | name | slot | id | species_id | +--------+------+-------+------------+ | Fire | 1 | 4 | 4 | | Fire | 1 | 5 | 5 | | Flying | 2 | 6 | 6 | | Flying | 2 | 10035 | 6 | | Fire | 1 | 6 | 6 | | Fire | 1 | 10034 | 6 | | Fire | 1 | 10035 | 6 | | Dragon | 2 | 10034 | 6 | | Fire | 1 | 390 | 390 | +--------+------+-------+------------+
I also tried with some simple code that only access the database with that query and I always get the same problem, here is the code:
#include <stdio.h>
#include <sqlite3.h>
// argument 1 is path to db, argument 2 is query
static int callback(void *NotUsed, int argc, char **argv, char **azColName){
int i;
for(i=0; i<argc; i++){
printf("%s\t", argv[i] ? argv[i] : "NULL");
}
printf("\n");
return 0;
}
int main(int argc, char **argv){
sqlite3 *db;
char *zErrMsg = 0;
int rc;
if( argc!=3 ){
fprintf(stderr, "Usage: %s DATABASE SQL-STATEMENT\n", argv[0]);
return(1);
}
rc = sqlite3_open(argv[1], &db);
if( rc ){
fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
sqlite3_close(db);
return(1);
}
rc = sqlite3_exec(db, argv[2], callback, 0, &zErrMsg);
if( rc!=SQLITE_OK ){
fprintf(stderr, "SQL error: %s\n", zErrMsg);
sqlite3_free(zErrMsg);
}
sqlite3_close(db);
return 0;
}
最佳答案
看起来你在期待:
SELECT name, slot, id, species_id
FROM type_names T, pokemon_types PT, pokemon P
WHERE T.type_id = PT.type_id
AND P.id = PT.pokemon_id
AND T.local_language_id = 9
AND P.identifier LIKE '%char%' ORDER BY P.species_id, id, slot ASC;
进一步限定您的 ORDER BY 以便能够准确复制结果。
关于SQLite 查询给出不同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23414848/