【问题标题】:SQLite How to add all string contents of a column to a single string (with condition)SQLite 如何将列的所有字符串内容添加到单个字符串(带条件)
【发布时间】:2019-03-04 10:49:28
【问题描述】:

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

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

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

TABLE AND STRING

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

Entries.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);

提前谢谢你!

【问题讨论】:

    标签: android sqlite android-recyclerview


    【解决方案1】:

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

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

    Demo

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

    【讨论】:

    • 没有帮助,我需要知道如何在我的代码中实现这一点
    • @RFM 是的,它确实有帮助,因为您可以从 Java 代码中执行此查询。与将所有信息引入 Java 并在那里进行聚合相比,直接在 SQLite 中进行这种聚合很可能会更有效。
    猜你喜欢
    • 1970-01-01
    • 2011-12-15
    • 1970-01-01
    • 2012-12-09
    • 2020-09-07
    • 1970-01-01
    • 2022-01-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多