小编典典

带有WHERE子句的UNION-Android Eclipse

java

我正在使用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 {

                }

        }



    });

}

阅读 213

收藏
2020-11-30

共1个答案

小编典典

未使用的参数的值为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() + "%" });
2020-11-30