[英]How to insert several values from one table to other table one column?
I'm creating android app and in one activity I need to create workout plan. 我正在创建android应用,并且在一项活动中我需要创建锻炼计划。 From spinner I'm choosing exercise name (which comes from other table). 从微调器中,我选择练习名称(来自其他表格)。 I can choose more than one exercise. 我可以选择多个练习。 So which way is the best to do it? 那么哪种方法最好呢? I tried adding several exercises to ArrayList and the save that ArrayList to database but I didn't find a way to do it. 我尝试将一些练习添加到ArrayList并将该ArrayList保存到数据库,但是我没有找到一种方法。 And I need to be able to edit workout plan(for example: delete or add exercises) so I think ArrayList is not a solution. 而且我需要能够编辑锻炼计划(例如:删除或添加锻炼),所以我认为ArrayList不是解决方案。
I realised that it's many to many relationship (a lot of exercises can be in a lot of workout plan) so I created table which contains exercise id and workout id: 我意识到这是多对多的关系(很多锻炼可以在很多锻炼计划中进行),所以我创建了包含锻炼ID和锻炼ID的表格:
private static final String CREATE_TABLE_TRAININGEXERCISE =
"CREATE TABLE " + TABLE_TRAININGEXERCISE + "(" + TEXERCISE_ID +
" INTEGER," + TWORKOUT_ID + " INTEGER," + "FOREIGN KEY (TExerciseID) REFERENCES "
+ TABLE_EXERCISE + " (ExerciseID)," +
" FOREIGN KEY (TWorkoutID) REFERENCES " + TABLE_WORKOUT + " (WorkoutID))";
}
I want my workout plan to look something like this: 我希望我的锻炼计划看起来像这样:
So how can I save these 3 exercises to one column? 那么如何将这3个练习保存到一栏?
Here's an example that does both what you ask, based upon you schema ie 这是一个示例,它根据您的架构来完成您所要求的
:- : -
2019-05-13 13:13:46.736 D/MYDATA: Workout: Chest
EXERCISES: Bench press,Incline bench press,Flies
2019-05-13 13:13:46.736 D/MYDATA: Workout: Abdomen
EXERCISES: hump,lug,roll
2019-05-13 13:13:46.736 D/MYDATA: Workout: Everything
EXERCISES: hump,lug,roll,kneel,Bench press,Incline bench press,Flies,Flip
The database helper, DBHelper.java used was :- 使用的数据库助手DBHelper.java是:-
public class DBHelper extends SQLiteOpenHelper {
public static final String DBNAME = "workout";
public static final int DBVERSION = 1;
public static final String TABLE_TRAININGEXERCISE = "training_excercise"; //<<<<<<<< OOOPS spelling :)
public static final String TABLE_WORKOUT = "workout";
public static final String TABLE_EXERCISE = "exersise"; //<<<<<<< OOOPS spelling :)
public static final String TWORKOUT_ID = "WorkoutID";
public static final String TWORKOUT_NAME = "workour_name";
public static final String TEXERCISE_ID = "ExerciseID";
public static final String TEXERCISE_NAME = "exercise_name";
public static final String TTEEXERCISELINK = "TExerciseID"; //<<<<<<<<<< ADDED
public static final String TTEWORKOUTLINK = "TWorkoutID"; //<<<<<<<<<< ADDED
// Note as entities are always derived from constants above the spelling mistakes are irrelvant
// (need a better smellchecker :) )
//<<<<<<<<<< ENOUGH TO DEMONSTRATE >>>>>>>>>>
private static final String CREATE_TABLE_WORKOUT =
"CREATE TABLE " + TABLE_WORKOUT + "(" +
TWORKOUT_ID + " INTEGER PRIMARY KEY," +
TWORKOUT_NAME + " TEXT" +
")";
//<<<<<<<<<< ENOUGH TO DEMONSTRATE >>>>>>>>>>
private static final String CREATE_TABLE_EXERCISE =
"CREATE TABLE " + TABLE_EXERCISE + "(" +
TEXERCISE_ID + " INTEGER PRIMARY KEY," +
TEXERCISE_NAME + " TEXT " +
")";
//<<<<<<<<<<NOTE Uses constants for all entity names >>>>>>>>>> (see new ones above)
private static final String CREATE_TABLE_TRAININGEXERCISE =
"CREATE TABLE " + TABLE_TRAININGEXERCISE + "(" +
TTEEXERCISELINK + " INTEGER," +
TTEWORKOUTLINK + " INTEGER," +
"FOREIGN KEY (" + TTEEXERCISELINK + ") " +
"REFERENCES " + TABLE_EXERCISE + " (" + TEXERCISE_ID + ")," +
" FOREIGN KEY (" + TTEWORKOUTLINK + ") " +
"REFERENCES " + TABLE_WORKOUT + " (" + TWORKOUT_ID + "))";
public DBHelper(Context context) {
super(context, DBNAME, null, DBVERSION);
}
@Override
public void onConfigure(SQLiteDatabase db) {
super.onConfigure(db);
db.setForeignKeyConstraintsEnabled(true); //<<<<<<<<<< MUST HAVE FOR FOREIGN KEYS
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_EXERCISE);
db.execSQL(CREATE_TABLE_WORKOUT);
db.execSQL(CREATE_TABLE_TRAININGEXERCISE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public long addWorkout(String name) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(TWORKOUT_NAME,name);
return db.insert(TABLE_WORKOUT,null,cv);
}
public long addExecise(String name) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(TEXERCISE_NAME,name);
return db.insert(TABLE_EXERCISE,null,cv);
}
public long addExcerciseToWorkout(long workoutid, long exerciseid) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(TTEWORKOUTLINK,workoutid);
cv.put(TTEEXERCISELINK,exerciseid);
return db.insert(TABLE_TRAININGEXERCISE,null,cv);
}
//<<<<<<<<<< ADD MANY EXERCISES to a WORKOUT via an ArrayList
public void addManyExcercisesToWorkout(long workoutid,ArrayList<Long> exerciseids) {
ArrayList<Long> rv = new ArrayList<>();
SQLiteDatabase db = this.getWritableDatabase();
db.beginTransaction();
for (Long l: exerciseids) {
long thisid = addExcerciseToWorkout(workoutid,l);
}
db.setTransactionSuccessful();
db.endTransaction();
}
//<<<<<<<<<< Get all the exercises per workout via the group_concat function >>>>>>>>>>
public void logAllWorkoutsWithExcercises() {
SQLiteDatabase db = this.getWritableDatabase();
//<<<<<<<<<< column name aliases (not required but desireable as they can be quite cumbersome) >>>>>>>>>>
String workoutname_column_alias = "thisworkoutname";
String concantenated_exercises_alias = "all_exercises";
String tables = TABLE_WORKOUT +
" JOIN " + TABLE_TRAININGEXERCISE + " ON " + TABLE_WORKOUT + "." + TWORKOUT_ID + "=" + TTEWORKOUTLINK +
" JOIN " + TABLE_EXERCISE + " ON " + TTEEXERCISELINK + "=" + TABLE_EXERCISE + "." + TEXERCISE_ID;
String[] columns = new String[]{
TABLE_WORKOUT + "." + TWORKOUT_NAME + " AS " + workoutname_column_alias,
"'\n\tEXERCISES: '||group_concat(" +
TABLE_EXERCISE + "." + TEXERCISE_NAME +
") AS " + concantenated_exercises_alias
};
String groupby = TABLE_WORKOUT + "." + TWORKOUT_ID;
// Query resolves to :-
/*
SELECT
workout.workour_name AS thisworkoutname,
'EXERCISES: '||group_concat(exersise.exercise_name) AS all_exercises
FROM workout
JOIN training_excercise ON workout.WorkoutID=TWorkoutID
JOIN exersise ON TExerciseID=exersise.ExerciseID
GROUP BY workout.WorkoutID
*/
Cursor csr = db.query(tables,columns,null,null,groupby,null,null);
while (csr.moveToNext()) {
Log.d(
"MYDATA",
"Workout: " +
csr.getString(csr.getColumnIndex(workoutname_column_alias)) +
csr.getString(csr.getColumnIndex(concantenated_exercises_alias))
);
}
csr.close();
}
}
The testing was done via an activity as per :- 测试是通过以下活动进行的:
public class MainActivity extends AppCompatActivity {
String[] allexcercises = new String[]{"hump", "lug", "roll", "kneel", "Bench press", "Incline bench press", "Flies","Flip"};
// Note assume that hump is id 1, lug id 2 etc
String[] allworkouts = new String[]{"Chest","Abdomen","Everything"};
ArrayList<Long> chest_excercises = new ArrayList<>();
ArrayList<Long> abdomen_excercises = new ArrayList<>();
ArrayList<Long> everything_excercises = new ArrayList<>();
DBHelper mDBHlpr;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDBHlpr = new DBHelper(this);
addSomeData(); //<<<<<<<<<< Adds the testing data (only designed to run once)
mDBHlpr.logAllWorkoutsWithExcercises(); //<<<<<<<<<< Output workouts with excercises
}
private void addSomeData() {
// Excercises
mDBHlpr.getWritableDatabase().beginTransaction();
for (String excercise: allexcercises) {
mDBHlpr.addExecise(excercise);
}
for (String workout: allworkouts) {
mDBHlpr.addWorkout(workout);
}
mDBHlpr.getWritableDatabase().setTransactionSuccessful();
mDBHlpr.getWritableDatabase().endTransaction();
// Build ArrayLists as if from multiple spinner selections
chest_excercises.add(new Long(5));
chest_excercises.add(new Long(6));
chest_excercises.add(new Long(7));
abdomen_excercises.add(new Long(1));
abdomen_excercises.add(new Long(2));
abdomen_excercises.add(new Long(3));
// Add all excercises to the everything workout ArrayList
for(int l=1; l <= allexcercises.length; l++) {
everything_excercises.add(new Long((long) l));
}
// Add multiple exercises per workout
mDBHlpr.addManyExcercisesToWorkout(1,chest_excercises);
mDBHlpr.addManyExcercisesToWorkout(2,abdomen_excercises);
mDBHlpr.addManyExcercisesToWorkout(3,everything_excercises);
}
}
You don't need to shove all exercises name into one column (which Contradicts the table scheme you created and will be hard to manipulate exercises if you do so), you need to insert each exercise into its own record in TABLE_TRAININGEXERCISE and link it to a single workout, the next step is to add an ArrayList into the workout model which you'll populate with a list of all exercises related to that same workout ID by using adding a method that fetches all records from TABLE_TRAININGEXERCISE using the workout ID. 您无需将所有练习名称都推到一栏中(这与您创建的表方案相矛盾,如果这样做,将很难进行操作),您需要将每个练习插入到TABLE_TRAININGEXERCISE中自己的记录中,并将其链接到一次锻炼,下一步是将ArrayList添加到锻炼模型中,通过使用添加使用锻炼ID从TABLE_TRAININGEXERCISE获取所有记录的方法,您将在其中填充与该锻炼ID相关的所有锻炼的列表。
That way you have its simpler to manipulate workout exercises (insert, update or delete) And you can achieve the desired output by printing the workout name and loop over its exercises and join them with a comma. 这样,您就可以更轻松地进行锻炼练习(插入,更新或删除),并且可以通过打印锻炼名称并遍历其锻炼并用逗号将其加入来实现所需的输出。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.