带有WHERE子句的UNION - Android Eclipse

时间:2014-12-02 15:29:32

标签: java android database eclipse sqlite

我使用UNION创建搜索界面以搜索多个表。我的问题是,当我尝试搜索单词时,最后一个表中的数据是唯一不断出现的数据。如何在条件适当的地方搜索表格,应根据其首字母搜索名称。

这是我的代码:

@Override
        public void onTextChanged(CharSequence s, int start, int before,
                int count) {
            // TODO Auto-generated method stub

            if (searchText.getText().toString().length() > 0) {
                cursor = db.rawQuery("SELECT _id AS _id, name AS name, desc AS desc FROM comm_acc  WHERE name LIKE ?" +
                        " UNION SELECT _id AS _id, name AS name, desc AS desc FROM comm_filems  WHERE name LIKE ? " +
                        "UNION SELECT _id AS _id, name AS name, desc AS desc FROM comm_psu  WHERE name LIKE ? " +
                        "UNION SELECT _id AS _id, name AS name, desc AS desc FROM comm_shells  WHERE name LIKE ? " +
                        "UNION SELECT _id AS _id, name AS name, desc AS desc FROM comm_sic  WHERE name LIKE ? " +
                        "UNION SELECT _id AS _id,name AS name, desc AS desc FROM comm_stp WHERE name LIKE ?", 
                        new String[]{searchText.getText().toString() + "%"});
                adapter = new SimpleCursorAdapter(
                getActivity(), 
                R.layout.search_command_list_item, 
                cursor, 
                new String[] {"name", "desc"}, 
                new int[] {R.id.commandName, R.id.commandDesc}, 0);
                setListAdapter(adapter);

                }
                else {

                }

        }



    });

}

1 个答案:

答案 0 :(得分:0)

未使用的参数获取NULL值;实际上只搜索了comm_acc表。

您必须为查询提供六个参数:

String searchPattern = searchText.getText().toString() + "%";
cursor = db.rawQuery("SELECT ... ? ... ? ... ? ... ? ... ? ... ? ...",
                     new String[]{ searchPattern, searchPattern, searchPattern,
                                   searchPattern, searchPattern, searchPattern });

或在所有LIKE中使用相同的参数:

cursor = db.rawQuery("          SELECT ... name LIKE ?1 " +
                     "UNION ALL SELECT ... name LIKE ?1 " +
                     ...
                     "UNION ALL SELECT ... name LIKE ?1",
                     new String[]{ searchText.getText().toString() + "%" });
相关问题