[英]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
如果您要返回多個字段,則可以在查詢中使用GROUP BY
,如下所示:
select id, Group_Concat(EmployeeName)
from table1
group by id
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.