首页 > 解决方案 > SQLite 如何将列的所有字符串内容添加到单个字符串(带条件)

问题描述

我正在使用 SQLite 开发一个应用程序,每一行都有一列名称字符串和一列检查器。基本上,我数据库中的每个人都有一个姓名和一个检查器,显示该人是否已申请课程。COLUMN_NAMES 有“ALEX”、“JASON”等字符串,COLUMN_CHECK 有“YES”或“NO”等字符串。

按一下按钮,我想生成一个像“ALEX、JASON、WALTER、TOM、HEISENBERG”这样的字符串,其中只有那些具有 COLUMN_CHECK 值“YES”的名称。

如果我没有让自己在上面理解,这是一个图像示例:

表格和字符串

我有一个名为 CRUD.class 的 DatabaseHelper 类,这些是我的类中的一些关键行:

Entry.class(数据类):

public static final String COLUMN_NAMES = "names";
public static final String COLUMN_CHECK = "check";

public static final String TABLE_NAME = "entries";
public static final String CREATE_TABLE =
        "CREATE TABLE " + TABLE_NAME + "("
                + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
                + COLUM_NAMES + " TEXT,"
                + COLUMN_CHECK + " TEXT"
                + ")";

public Entry() {
}

public Entry(int id, String names, String check) {
    this.id = id;
    this.names = names;
    this.check = check;
}

public int getId() { return id; }
public void setId(int id){ this.id = id; }

public String getNames() { return names; }
public void setNames(String names){ this.names = names; }

public String getCheck() { return check; }
public void setCheck(String check){ this.check = check; }

MainActivity.class:

  private EntryAdapter mAdapter;
    private List<Entry> entryList = new ArrayList<>();
    private RecyclerView recyclerView;
    private CRUD db;


        db = new CRUD(this);
        entryList.addAll(db.getAllEntries());

        mAdapter = new EntryAdapter(this, entryList);
        RecyclerView.LayoutManager mLayoutManager = new 
        LinearLayoutManager(getApplicationContext());
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setAdapter(mAdapter);

先感谢您!

标签: androidsqliteandroid-recyclerview

解决方案


你可以在这里使用 SQLite 的GROUP_CONCAT函数:

SELECT GROUP_CONCAT(names) AS names_csv
FROM entries
WHERE "check" = 'YES';

在此处输入图像描述

演示

旁注:请避免在表和列名称中使用 SQLite 关键字check。要使上述查询正常工作,您必须check用双引号转义。


推荐阅读