我必须执行一个简单的查询,如:
SELECT messages.*, contacts.nick FROM messages INNER JOIN contacts ON contacts.userId = messages.userId WHERE messages.isListened=0
其中isListened
被声明为INTEGER
:
"CREATE TABLE IF NOT EXISTS " + Tables.Messages.TABLE_NAME + " (" +
...
Tables.Messages.IS_LISTENED + " INTEGER, " +
...
我无法让它发挥作用。我已经尝试过了:
private static final String getAllMessagesSQL =
"SELECT "
+Tables.Messages.TABLE_NAME+".*, "
+Tables.Contacts.TABLE_NAME+"."+Tables.Contacts.NICK
+" FROM "+Tables.Messages.TABLE_NAME
+" INNER JOIN "+Tables.Contacts.TABLE_NAME
+" ON "+Tables.Contacts.TABLE_NAME+"."+Tables.Contacts.USER_ID+" = "
+ Tables.Messages.TABLE_NAME+"."+Tables.Messages.SENDER_USER_ID
+" WHERE "+Tables.Messages.TABLE_NAME+"."+Tables.Messages.IS_LISTENED+"='0'";
public void getAllMessages(final List<Message> list) {
SQLiteDatabase db = null;
Message message = null;
Cursor cursor = null;
try {
db = dbAdapter.openToRead();
cursor = db.rawQuery(getAllMessagesSQL, null);
Log.w(this,"getAllMessages(): \nsql: "+getAllMessagesSQL+"\ncursor.getCount(): "+cursor.getCount());
if (cursor.moveToFirst()){
list.clear();
while (!cursor.isAfterLast()) {
Log.w(this, "getAllMessages() message.IS_LISTENED: "+cursor.getInt(cursor.getColumnIndex(Tables.Messages.IS_LISTENED)));
message = getMessageFromCursor(cursor);
list.add(message);
cursor.moveToNext();
}
}
...
结果是:
05-26 11:06:20.706: W/DatabaseHelper(3352): getAllMessages():
05-26 11:06:20.706: W/DatabaseHelper(3352): sql: SELECT messages.*, contacts.nick FROM messages INNER JOIN contacts ON contacts.userId = messages.userId WHERE messages.isListened='0'
05-26 11:06:20.706: W/DatabaseHelper(3352): cursor.getCount(): 0
此外,我在没有引用0:
的情况下尝试了WHERE
子句
...
+" WHERE "+Tables.Messages.TABLE_NAME+"."+Tables.Messages.IS_LISTENED+"=0";
...
以适当的方式:
...
+" WHERE "+Tables.Messages.TABLE_NAME+"."+Tables.Messages.IS_LISTENED+"=?";
...
cursor = db.rawQuery(getAllMessagesSQL, new String[]{"0"});
和结果是相同的 - 0记录,而我知道其中有2个
为了确保我注释掉WHERE
条款,如:
... + Tables.Messages.TABLE_NAME+"."+Tables.Messages.SENDER_USER_ID;
//+" WHERE "+Tables.Messages.TABLE_NAME+"."+Tables.Messages.IS_LISTENED+"='0'";
....
然后我得到了以下输出:
05-26 11:12:14.046: W/DatabaseHelper(3635): getAllMessages():
05-26 11:12:14.046: W/DatabaseHelper(3635): sql: SELECT messages.*, contacts.nick FROM messages INNER JOIN contacts ON contacts.userId = messages.userId
05-26 11:12:14.046: W/DatabaseHelper(3635): cursor.getCount(): 2
05-26 11:12:14.046: W/DatabaseHelper(3635): getAllMessages() message.IS_LISTENED: 0
05-26 11:12:14.046: W/DatabaseHelper(3635): getAllMessages() message.IS_LISTENED: 0
因此,如果没有使用WHERE子句,可以看到有2个匹配匹配 那么为什么WHERE caluse在这里不起作用?
答案 0 :(得分:3)
尝试WHERE "+Tables.Messages.TABLE_NAME+"."+Tables.Messages.IS_LISTENED+"=0 OR " +Tables.Messages.TABLE_NAME+"."+Tables.Messages.IS_LISTENED+" IS NULL"
或更改
"CREATE TABLE IF NOT EXISTS " + Tables.Messages.TABLE_NAME + " (" +
...
Tables.Messages.IS_LISTENED + " INTEGER NOT NULL, " +
...