我有3张桌子
表1:成员 - 存储有关成员的所有信息,
属性:MemberUsername(PK),MemberPassword
表2:MsGroup - 存储每个注册的组
属性:GroupId(PK),GroupName,GroupDescription
表3:MsGroupDetail - 存储每个组中每个用户名的列表
属性:GroupId(PK,FK),MemberUsername(PK,FK)
我创建3个表的查询:
db.execSQL("CREATE TABLE IF NOT EXISTS " + MS_MEMBER + " ("
+ MEMBER_USERNAME + " TEXT PRIMARY KEY NOT NULL, "
+ MEMBER_PASSWORD + " TEXT NOT NULL, " + MEMBER_EMAIL
+ " TEXT NOT NULL" + ");");
db.execSQL("CREATE TABLE IF NOT EXISTS " + MS_GROUP + " ("
+ GROUP_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ GROUP_NAME + " TEXT NOT NULL, " + GROUP_DESCRIPTION
+ " TEXT NOT NULL);");
db.execSQL("CREATE TABLE IF NOT EXISTS " + MS_GROUP_DETAIL + " ("
+ GROUP_ID + " INTEGER PRIMARY KEY, " + MEMBER_USERNAME
+ " TEXT, FOREIGN KEY (" + MEMBER_USERNAME
+ ") REFERENCES " + MS_MEMBER + "(" + MEMBER_USERNAME
+ "), FOREIGN KEY (" + GROUP_ID + ") REFERENCES "
+ MS_GROUP + "(" + GROUP_ID + "));");
我已成功创建一些代码来创建成员,创建组,但问题是我无法创建查询以邀请/添加新成员到组(无法插入到MsGroupDetail)
这是添加GroupMember
的语法public void addGroupMember(String groupId, String username) {
// TODO Auto-generated method stub
ContentValues cv2 = new ContentValues();
cv2.put(GROUP_ID, groupId);
cv2.put(MEMBER_USERNAME, username);
ourDatabase.insert(MS_GROUP_DETAIL, null, cv2);
}
这是查看我的论坛列表的语法
public String[] fetchGroupName(String username) {
int i = 0;
String Query = "SELECT " + GROUP_NAME + " From " + MS_GROUP
+ " a INNER JOIN " + MS_GROUP_DETAIL + " b ON a." + GROUP_ID
+ "=b." + GROUP_ID + " WHERE " + MEMBER_USERNAME + "=?";
Cursor c = ourDatabase.rawQuery(Query, new String[] { username });
String groupName[] = new String[c.getCount()];
int iGroupName = c.getColumnIndex(GROUP_NAME);
c.moveToFirst();
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
groupName[i] = c.getString(iGroupName);
i++;
}
c.close();
return groupName;
}
每次我邀请一个新成员/添加到MsGroupDetail表时,我都无法将其插入MsGroupDetail并且日志猫说:“SQLite约束异常,主键必须是唯一的”
* nb:我的MsGroupDetail再一次列出一个组内的每个成员,
我在Sql Server Management Studio 2008中测试了相同的概念并且它有效,我不知道比上面编码的更好的概念,
你能告诉我有什么解决办法吗?
非常感谢你..
答案 0 :(得分:1)
问题是您的GROUP_ID
不是唯一的。如果组1中有两个成员,则表将有两个条目 -
1, Member 1
1, Member 2
通过指定" PRIMARY KEY"在GROUP_ID
,你说它将是独一无二的。您需要不同的主键。在android中,通常使用" _id",类似于
db.execSQL("CREATE TABLE IF NOT EXISTS " + MS_GROUP_DETAIL + " ("
+ "_id INTEGER PRIMARY KEY AUTOINCREMENT,"
+ GROUP_ID + " INTEGER, " + MEMBER_USERNAME
+ " TEXT, FOREIGN KEY (" + MEMBER_USERNAME
+ ") REFERENCES " + MS_MEMBER + "(" + MEMBER_USERNAME
+ "), FOREIGN KEY (" + GROUP_ID + ") REFERENCES "
+ MS_GROUP + "(" + GROUP_ID + "));");