如何实现Android Sqlite Union rawQuery?

时间:2015-09-27 05:41:01

标签: android sqlite

我使用以下代码搜索专栏"英语"。还有一个名为" BANGLA"的专栏。我应该如何修改代码,以便" ENGLISH"和" BANGLA"同时搜索列并作为组合结果返回?

public List<Bean> getWords(String englishWord) {
        if(englishWord.equals(""))
            return new ArrayList<Bean>();

        String sql = "SELECT * FROM " + TABLE_NAME +
                " WHERE " + ENGLISH + " LIKE ? ORDER BY " + ENGLISH + " LIMIT 100 ";

        SQLiteDatabase db = initializer.getReadableDatabase();

        Cursor cursor = null;
        try {
            cursor = db.rawQuery(sql, new String[]{"%" + englishWord + "%"});

            List<Bean> wordList = new ArrayList<Bean>();
            while(cursor.moveToNext()) {
                int id = cursor.getInt(0);
                String english = cursor.getString(1);
                String bangla = cursor.getString(2);
                String status = cursor.getString(3);
                wordList.add(new Bean(id, english, bangla, status));
            }

            return wordList;
        } catch (SQLiteException exception) {
            exception.printStackTrace();
            return null;
        } finally {
            if (cursor != null)
                cursor.close();
        }
    }

我将String sql修改为

String sql = "SELECT * FROM " + TABLE_NAME +
                " WHERE " + ENGLISH + " LIKE ? ORDER BY " + ENGLISH + " LIMIT 100 " + " UNION ALL " + " SELECT * FROM " + TABLE_NAME +
                " WHERE " + BANGLA + " LIKE ? ORDER BY " + ENGLISH + " LIMIT 100";

然而,这不起作用。我收到了这个错误:

ORDER BY clause should come after UNION ALL not before (code 1): , while compiling: SELECT * FROM words WHERE en_word LIKE ? ORDER BY en_word LIMIT 100  UNION ALL  SELECT * FROM words WHERE bn_word LIKE ? ORDER BY en_word LIMIT 100

1 个答案:

答案 0 :(得分:1)

你需要将ORDER BY和LIMIT移到最后:

SELECT * FROM TABLE_NAME
WHERE ENGLISH LIKE ?
UNION ALL 
SELECT * FROM tull
WHERE BANGLA LIKE ?
ORDER BY ENGLISH LIMIT 100

然而,这只会按英文排序,并且总共限制为100行。你是否需要每种语言100行?如果您想按两种语言订购,您可以使用别名对列进行别名并按顺序排序:

SELECT *, ENGLISH AS TEXT FROM tull
WHERE ENGLISH LIKE ? OR BANGLA LIKE ?
UNION ALL 
SELECT *, BANGLA AS TEXT FROM tull
WHERE BANGLA LIKE "" 
ORDER BY TEXT LIMIT 100;

您仍然需要将第二个选择参数添加为评论中提到的jyank。