繁体   English   中英

Concat数据库表1字段多行记录在一行中

[英]Concat database tables 1 field multiple records string in one row

我有一个表和记录,如:

EmployeeName
------------
Ram
Laxman
Bharat
Shatrugn

我想在单个查询中输出以合并所有值的地方:

我想要这样的结果:

Ram,Laxman,bharat,shatrugn

Concat字符串,在单行中带有(,逗号)。但是我不知道如何使用光标在Android中进行concat ...

在SQLite中,可以使用GROUP_CONCAT()

select Group_Concat(EmployeeName)
from table1

参见带有演示的SQL Fiddle

如果您要返回多个字段,则可以在查询中使用GROUP BY ,如下所示:

select id, Group_Concat(EmployeeName)
from table1
group by id

参见带有演示的SQL Fiddle

     String values;
       if (cursor.moveToFirst()) {
                do {

               values=values + cursor.getString(0)+",";

                } while (cursor.moveToNext());

删除最后一个逗号

if (values.length() > 0)
 {
    values= values.substring(0,values.length() - 1);    
  }

这是我使用的代码...希望对您有所帮助。

 private SQLiteDatabase myDataBase;
 Cursor cursor;
 String S="";
 String myPath2 = yourDBpath + yourDBNAME;
 try{
 myDataBase = SQLiteDatabase.openDatabase(myPath2, null,SQLiteDatabase.OPEN_READWRITE);
 String sql="your query";
 cursor=myDataBase.rawQuery(sql, null);
if(cursor != null)
{
   while(cursor.moveToNext())
   {
    S=S.append(cursor.getString(0));
    }
}
  } 
}catch(Exception e){

        }finally{
        myDataBase.close();
        }

最终结果将在字符串S中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM