SQLiteDatabase在查询中需要帮助...请

时间:2013-10-31 17:53:13

标签: android sqlite android-sqlite

我有这张桌子:

id | CUPNAME | FRENCHNAME
1  | 2       | null
2  | null    | 4

我想从CUPNAME和FRENCHNAME中提取非空的数据。 该表可以填充1到10之间的数字。在此示例中,应该能够CUPNAME = 2,FRENCHNAME = 4.

有这样的疑问:

SELECT sum(ifnull(french_press_bd.CUPNAME,0)) as a , sum(ifnull(french_press_bd.FRENCHNAME,0)) as b FROM my_table WHERE id in (1,2)

我尝试写这样不起作用:

 String sqr = "id in (1,2)";
Cursor cursor = sqdb.query(french_press_bd.TABLE_NAME, new String[] {                   
"sum(ifnull(french_press_bd.CUPNAME,0)) as a , sum(ifnull(french_press_bd.FRENCHNAME,0)) as b" 
},sqr, null,null,null,null );

2 个答案:

答案 0 :(得分:1)

我认为你可以使用rawQuery。为:

String your_query= "SELECT sum(ifnull(french_press_bd.CUPNAME,0)) as a , sum(ifnull(french_press_bd.FRENCHNAME,0)) as b FROM my_table WHERE id in (1,2)";
Cursor result = sqdb.rawQuery(your_query, null);

但请确保SQLiteDatabase不是NULL。你必须在它之前打电话,

sqdb = dbhelper.getReadableDatabase(); // or getWritableDatabase()

答案 1 :(得分:0)

此查询使用两个标量子查询从相应列中获取第一个非NULL值:

SELECT (SELECT CUPNAME
        FROM my_table
        WHERE id IN (1, 2)
          AND CUPNAME IS NOT NULL
       ) AS CUPNAME,
       (SELECT FRENCHNAME
        FROM my_table
        WHERE id IN (1, 2)
          AND FRENCHNAME IS NOT NULL
       ) AS FRENCHNAME;

由于外部查询实际上没有做任何事情,因此单独执行两个查询可能更简单:

long cName = db.compileStatement("SELECT CUPNAME FROM my_table" +
                                 " WHERE id IN (1, 2) AND CUPNAME IS NOT NULL"
                                ).simpleQueryForLong();
long fName = db.compileStatement("SELECT FRENCHNAME FROM my_table" +
                                 " WHERE id IN (1, 2) AND FRENCHNAME IS NOT NULL"
                                ).simpleQueryForLong();