在我的数据库中,我有两个表“classes”和“classes_sessions”,我创建了一个链接两个表的外键。我正在尝试使用下面的查询从这些表中检索数据
代码
String selectQuery = "SELECT * FROM " +
TABLE_CLASSES +
" INNER JOIN " + TABLE_CLASSES_SECTIONS +
" ON " +
TABLE_CLASSES_SECTIONS + "." + COLUMN_CLASSES_SECTIONS_ID +
" = " + TABLE_CLASSES + "." + COLUMN_CLASSES_SECTIONS +
" WHERE " +
TABLE_CLASSES + "." + COLUMN_CLASSES_ID +
" = " + String.valueOf(id);
在下面的getAllSectionsByClassesID()
方法中
public ArrayList<SectionsBean> getAllSectionsByClassesID(long id){
String selectQuery = "SELECT * FROM " +
TABLE_CLASSES +
" INNER JOIN " + TABLE_CLASSES_SECTIONS +
" ON " +
TABLE_CLASSES_SECTIONS + "." + COLUMN_CLASSES_SECTIONS_ID +
" = " + TABLE_CLASSES + "." + COLUMN_CLASSES_SECTIONS +
" WHERE " +
TABLE_CLASSES + "." + COLUMN_CLASSES_ID +
" = " + String.valueOf(id);
SQLiteDatabase db = this.getReadableDatabase();
ArrayList<SectionsBean> sectionsBeanList = new ArrayList<SectionsBean>();
Cursor cursor = db.rawQuery(selectQuery,null);
Log.i("Query details", String.valueOf(cursor));
Log.d("DataDetails", DatabaseUtils.dumpCursorToString(cursor));
while (cursor.moveToNext()) {
ClassesBean classesBean = new ClassesBean();
classesBean.setId(cursor.getLong(cursor.getColumnIndex(COLUMN_CLASSES_ID)));
classesBean.setClasses_name(cursor.getString(cursor.getColumnIndex(COLUMN_CLASSES_NAME)));
SectionsBean sectionsBean = new SectionsBean();
sectionsBean.setSectionsID(cursor.getLong(cursor.getColumnIndex(COLUMN_CLASSES_SECTIONS_ID)));
sectionsBean.setSections_name(cursor.getString(cursor.getColumnIndex(COLUMN_CLASSES_SECTIONS_NAME)));
sectionsBean.setClassesBean(classesBean);
sectionsBeanList.add(sectionsBean);
}
return sectionsBeanList;
}
但它不会返回任何东西。我正在使用该行来检查光标在数据库Log.d("DataDetails", DatabaseUtils.dumpCursorToString(cursor));
中返回的数据,结果为空。两个表中的内容如下所示
数据库内容
班级表
-05 22:06:23.728 31258-31310/com.example.demeainc.demea D/DataC: >>>>> Dumping cursor android.database.sqlite.SQLiteCursor@88a8264
0 {
classes_id=1
class_item_index=null
classes_name=jss1
classes_codename=null
classes_sections_id=null
classes_teachers=null
classes_students=null
}
1 {
classes_id=2
class_item_index=null
classes_name=villa
classes_codename=null
classes_sections_id=null
classes_teachers=null
classes_students=null
}
2 {
classes_id=3
class_item_index=null
classes_name=two
classes_codename=null
classes_sections_id=null
classes_teachers=null
classes_students=null
}
<<<<<
会话表的数据库内容
03-05 22:09:03.943 31258-31258/com.example.demeainc.demea D/DataS: >>>>> Dumping cursor android.database.sqlite.SQLiteCursor@eaadf23
0 {
classes_sections_ids=1
classes_sections_name=cooolanet
classes_sections_description=bbdbn
}
1 {
classes_sections_ids=2
classes_sections_name=morrals
classes_sections_description=mills
}
2 {
classes_sections_ids=3
classes_sections_name=live
classes_sections_description=bxn
}
3 {
classes_sections_ids=4
classes_sections_name=testing2
classes_sections_description=coll
}
4 {
classes_sections_ids=5
classes_sections_name=tool
classes_sections_description=vi
}
5 {
classes_sections_ids=6
classes_sections_name=colls
classes_sections_description=
}
6 {
classes_sections_ids=7
classes_sections_name=more
classes_sections_description=coll
}
7 {
classes_sections_ids=8
classes_sections_name=testing
classes_sections_description=ttt
}
8 {
classes_sections_ids=9
classes_sections_name=threevill
classes_sections_description=cool
}
<<<<<
有关创建表的更多详细信息。
// create classes_table sql query
private String CREATE_CLASSES_TABLE = "CREATE TABLE IF NOT EXISTS " + TABLE_CLASSES + "("
+ COLUMN_CLASSES_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + COLUMN_CLASS_ITEM_INDEX + " NUMBER,"
+ COLUMN_CLASSES_NAME + " VARCHAR," + COLUMN_CLASSES_CODENAME + " VARCHAR, " + COLUMN_CLASSES_SECTIONS + " INTEGER," + COLUMN_CLASSES_TEACHERS
+ " VARCHAR," + COLUMN_CLASSES_STUDENTS + " VARCHAR,"
+ "FOREIGN KEY(" + COLUMN_CLASSES_SECTIONS + ") REFERENCES " + TABLE_CLASSES_SECTIONS + "(" + COLUMN_CLASSES_SECTIONS_ID + ") ON DELETE CASCADE " + ");";
//create sections sql query
private String CREATE_CLASSES_SECTIONS_TABLE = "CREATE TABLE IF NOT EXISTS " + TABLE_CLASSES_SECTIONS + "("
+ COLUMN_CLASSES_SECTIONS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + COLUMN_CLASSES_SECTIONS_NAME + " VARCHAR,"
+ COLUMN_CLASSES_SECTIONS_DESCRIPTION + " VARCHAR" + ")";
可能是什么问题。外键实际上是链接两个表。我在上面的代码中出了什么问题。
答案 0 :(得分:1)
您的问题是 class_sections_id 列为空,因此classes_sections_table(sessions表)中从不存在匹配的条目,因此没有创建JOIN,因此无需显示任何内容。
作为一个如何工作的示例,请使用以下类表: -
对于英语,您会看到 classes_sections_id 的值 1 这可以对应(也就是与/ reference等相关联)classes_sections_ids列,其值为 1 强>
查询
SELECT * FROM classes
INNER JOIN classes_sections
ON classes_sections.classes_sections_ids = classes.classes_sections_id
WHERE classes.classes_id =1
会导致: -
但是,如果将以下行添加到classes表中(请注意,对classes_sections_id列的引用的值为700,并且classes_sections表中没有这样的行): - < / p>
如果查询已更改为获取ID 4 ,则不会返回任何行,因为即使在类表中存在id 4(化学),也没有关联 classes_sections 行( classes_sections_ids 为 700 )因此没有JOIN,因此没有要返回的行。< / p>
简而言之,您需要将 sections_id 列引用/关联/链接到 classes_sections_ids 列以检索任何数据。
外键是否实际链接了两个表。
指定FOREIGN KEY仅指定存在约束(注意ON DELETE CASCADE
限制约束)。它不会自动定义链接,您必须这样做。
您可能以编程方式执行此操作(我手动完成上述链接),例如添加类时,您可以选择一个可用的部分,也许通过微调器(也称为下拉选择器)呈现。然后插入具有所选部分的id的类。
我认为您的设计问题最终会主要归因于您的引用/链接方式。
例如,您的设计有一个类表,其中包含一个链接到sections表的列。这不会引入处理单个列中的链接列表的复杂性,这限制了一个类只有一个部分(同样适用于教师和学生)。
基于假设一个类可能有多个部分然后进一步考虑,可以由许多类使用一个部分(例如,所有类必须以疏散程序开始)。
如果后者不适用,那么类和部分之间的关系可以是一对多(或者可以通过许多关系来处理)。
如果后者适用,那么类和部分之间的关系将是/应该是多个关系。
因此我建议您考虑以下设计(可能还会有更多): -
DROP TABLE IF EXISTS classes;
CREATE TABLE IF NOT EXISTS classes ( class_id INTEGER PRIMARY KEY, class_name TEXT, class_codename TEXT );
DROP TABLE IF EXISTS sections;
CREATE TABLE IF NOT EXISTS sections ( section_id INTEGER PRIMARY KEY, section_name TEXT, section_description TEXT);
DROP TABLE IF EXISTS teachers;
CREATE TABLE IF NOT EXISTS teachers ( teacher_id INTEGER PRIMARY KEY, teacher_name TEXT);
DROP TABLE IF EXISTS students;
CREATE TABLE IF NOT EXISTS students ( student_id INTEGER PRIMARY KEY, student_name TEXT);
-- LINK TABLES
-- Note usess column constraints to define foreign keys i.e. REFERENCES
DROP TABLE IF EXISTS class_section_links;
CREATE TABLE IF NOT EXISTS class_section_links (
class_link INTEGER NOT NULL REFERENCES classes (class_id),
section_link INTEGER NOT NULL REFERENCES sections (section_id),
PRIMARY KEY (class_link, section_link));
DROP TABLE IF EXISTS class_teacher_links;
CREATE TABLE IF NOT EXISTS class_teacher_links (
class_link INTEGER NOT NULL REFERENCES classes (class_id),
teacher_link INTEGER NOT NULL REFERENCES teachers (teacher_id),
PRIMARY KEY (class_link, teacher_link));
DROP TABLE IF EXISTS class_student_links;
CREATE TABLE IF NOT EXISTS class_student_links (
class_link INTEGER NOT NULL REFERENCES classes (class_id),
student_link INTEGER NOT NULL REFERENCES students (student_id),
PRIMARY KEY (class_link, student_link));
这将加载一些数据,包括类和部分之间的一些基本链接: -
-- LOAD some data
-- CLASSES
INSERT INTO classes (class_name, class_codename) VALUES('English Language','EL100');
INSERT INTO classes (class_name, class_codename) VALUES('English Literature','EL101');
INSERT INTO classes (class_name, class_codename) VALUES('Applied Mathermatics','MA200');
INSERT INTO classes (class_name, class_codename) VALUES('Pure Mathematics','MA201');
INSERT INTO classes (class_name, class_codename) VALUES('Chemistry','SC300');
INSERT INTO classes (class_name, class_codename) VALUES('Physics','SC301');
INSERT INTO classes (class_name, class_codename) VALUES('Biology','SC302');
INSERT INTO classes (class_name, class_codename) VALUES('GEOGRAPHY','GE400');
-- SECTIONS
INSERT INTO sections (section_name, section_description) VALUES('Class Introduction','Evacuation procedures, amenities etc..');
INSERT INTO sections (section_name, section_description) VALUES('Sentence Construction','Blah');
INSERT INTO sections (section_name, section_description) VALUES('Word types','Basic word types such as VERB, ADJECTIVE etc');
INSERT INTO sections (section_name, section_description) VALUES('Puntuation','Blah');
INSERT INTO sections (section_name, section_description) VALUES('Under Milk Wood','Blah');
INSERT INTO sections (section_name, section_description) VALUES('Catcher in the Rye','Blah');
INSERT INTO sections (section_name, section_description) VALUES('The War of the Worlds','Blah');
-- CLASS SECTION LINKS (note assumes ID's of classes/sections in order 1,2,3......)
-- a) All classes have Class Introduction
INSERT INTO class_section_links VALUES(1,1); -- Class 1 English language
INSERT INTO class_section_links VALUES(2,1); -- Class 2 English Lit
INSERT INTO class_section_links VALUES(3,1);
INSERT INTO class_section_links VALUES(4,1);
INSERT INTO class_section_links VALUES(5,1);
INSERT INTO class_section_links VALUES(6,1);
INSERT INTO class_section_links VALUES(7,1);
INSERT INTO class_section_links VALUES(8,1);
-- b) specific sections
INSERT INTO class_section_links VALUES(1,2); -- Class 1 has section 2
INSERT INTO class_section_links VALUES(1,3); -- Class 1 has section 3
INSERT INTO class_section_links VALUES(2,4);
INSERT INTO class_section_links VALUES(2,5);
INSERT INTO class_section_links VALUES(2,6);
INSERT INTO class_section_links VALUES(2,7);
查询,例如: -
SELECT class_name, class_codename, section_name, section_description
FROM class_section_links
JOIN classes ON class_link = class_id
JOIN sections ON section_link = section_id
ORDER BY class_name, section_name;
会导致: -
如果你看类介绍,你会发现只有一个部分被多次使用,因此只需要一组数据。因此,如果有指令而不是类介绍,则将其更改为简介,那么单个更改将更新所有类。
e.g。使用以下命令执行更新: -
UPDATE sections SET section_name = 'Introduction' WHERE section_name = 'Class Introduction';
并运行相同的查询结果: -
答案 1 :(得分:1)
虽然不是这个问题的答案,但这可能是有用的。
这是一个快速整理的演示,演示了如何在App中实现链接表。请注意,它非常简陋。
该应用最初将允许输入类(要求两个字段都有数据),单击添加类按钮将尝试添加类(如果两个输入都至少有1个字符。)
当添加一个类时,有三个额外的输入可用(可见),另外还会列出添加的类。新的输入是: -
当添加了一个部分时,该部分将在右侧列出,另外,组合的链接数据将列在列和部分列表的下方。
e.g。
(注意包名称必须更改)
<TextView
android:id="@+id/heading"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<EditText
android:id="@+id/class_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<EditText
android:id="@+id/class_codename"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="@+id/addclass"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add Class"/>
<EditText
android:id="@+id/section_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<EditText
android:id="@+id/section_description"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Spinner
android:id="@+id/classselection"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</Spinner>
<Button
android:id="@+id/addsection"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add Section"/>
<LinearLayout
android:orientation="horizontal"
android:id="@+id/lists"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ListView
android:id="@+id/classlist"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content">
</ListView>
<ListView
android:id="@+id/sectionlist"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"></ListView>
</LinearLayout>
<ListView
android:id="@+id/classsectionsinfo"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</ListView>
public class DBHelper extends SQLiteOpenHelper {
public static final String DBNAME = "educator";
public static final int DBVERSION = 1;
public static final String TB_CLASSES = "classes";
public static final String TB_SECTIONS = "sections";
public static final String TB_CLASS_SECTION_LINKS = "class_section_links";
public static final String COL_CLASSID = BaseColumns._ID;
public static final String COl_CLASSNAME = "class_name";
public static final String COl_CLASSCODENAME = "class_codename";
public static final String COL_SECTIONID = BaseColumns._ID;
public static final String COL_SECTIONNAME = "section_name";
public static final String COL_SECTIONDESCRIPTION = "section_description";
public static final String COL_CLASSLINK = "class_link";
public static final String COL_SECTIONLINK = "section_link";
public static final String COL_COMBINED = "info";
SQLiteDatabase mDB;
public DBHelper(Context context) {
super(context, DBNAME, null, DBVERSION);
mDB = this.getWritableDatabase();
}
@Override
public void onCreate(SQLiteDatabase db) {
String crttab = "CREATE TABLE IF NOT EXISTS ";
String crtclasses = crttab + TB_CLASSES +
"(" +
COL_CLASSID + " INTEGER PRIMARY KEY, " +
COl_CLASSNAME + " TEXT, " +
COl_CLASSCODENAME + " TEXT " +
")";
String crtsections = crttab + TB_SECTIONS +
"(" +
COL_SECTIONID + " INTEGER PRIMARY KEY, " +
COL_SECTIONNAME + " TEXT, " +
COL_SECTIONDESCRIPTION + " TEXT " +
")";
String crtclasssectionlink = crttab + TB_CLASS_SECTION_LINKS +
"(" +
COL_CLASSLINK + " INTEGER " +
" REFERENCES " + TB_CLASSES + "(" + COL_CLASSID + ")," +
COL_SECTIONLINK + " INTEGER " +
" REFERENCES " + TB_SECTIONS + "(" + COL_SECTIONID + ") " +
")";
db.execSQL(crtclasses);
db.execSQL(crtsections);
db.execSQL(crtclasssectionlink);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public long addClass(String classname, String classcode) {
if (classname.length() < 1 || classcode.length() < 1) {
return -1;
}
ContentValues cv = new ContentValues();
cv.put(COl_CLASSNAME,classname);
cv.put(COl_CLASSCODENAME,classcode);
return mDB.insert(TB_CLASSES,null, cv);
}
public long addSection(String sectioname, String sectiondescription, long baseclass) {
long sectionid = -1;
if (sectioname.length() < 1 || sectiondescription.length() < 1) {
return -1;
}
ContentValues cv = new ContentValues();
cv.put(COL_SECTIONNAME,sectioname);
cv.put(COL_SECTIONDESCRIPTION,sectiondescription);
sectionid = mDB.insert(TB_SECTIONS,null,cv);
if (sectionid > 0 && baseclass > 0) {
cv.clear();
cv.put(COL_CLASSLINK,baseclass);
cv.put(COL_SECTIONLINK,sectionid);
mDB.insert(TB_CLASS_SECTION_LINKS,null,cv);
}
return sectionid;
}
public Cursor getClassAndSectionDetailsCombined() {
//SELECT class_name||class_codename||section_name||section_description AS info
// FROM class_section_links
// JOIN classes ON class_link = classes._id
// JOIN sections ON section_link = sections._id
// ORDER BY class_name, section_name;
return mDB.query(
TB_CLASS_SECTION_LINKS +
" JOIN " + TB_CLASSES + " ON " +
COL_CLASSLINK + " = " + TB_CLASSES + "." + COL_CLASSID +
" JOIN " + TB_SECTIONS + " ON " +
COL_SECTIONLINK + " = " + TB_SECTIONS + "." + COL_SECTIONID,
new String[] {
COl_CLASSNAME + "||" +
COl_CLASSCODENAME + "||" +
COL_SECTIONNAME + "||" +
COL_SECTIONDESCRIPTION +
" AS " + COL_COMBINED,
"1 AS " + BaseColumns._ID},
null,null,null, null,
COl_CLASSNAME + "," + COL_SECTIONNAME
);
}
public Cursor getClasses() {
return mDB.query(TB_CLASSES,null,null,null,null,null,null);
}
public Cursor getSections() {
return mDB.query(TB_SECTIONS,null,null,null,null,null,null);
}
public long getSectionsCount() {
return DatabaseUtils.queryNumEntries(mDB,TB_SECTIONS);
}
public long getClassesCount() {
return DatabaseUtils.queryNumEntries(mDB,TB_CLASSES);
}
}
getClassAndSectionDetailsCombined
与注释SQL略有不同,因为游标有两列,一列是 _id ,这是为了方便使用需要_id列的CursorAdapters。
public class MainActivity extends AppCompatActivity {
EditText mClassName, mClassCode, mSectionName, mSectionDescription;
Button mAddClass, mAddSection;
ListView mClassList, mSectionList, mClassSectionInfoList;
Spinner mClassSelection;
DBHelper mDBHlpr;
Cursor mClasses, mSections, mCLassSectionInfo;
SimpleCursorAdapter mSCAClasses, mSCASections, mSCAClassSecInfo;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mClassName = (EditText) this.findViewById(R.id.class_name);
mClassCode = (EditText) this.findViewById(R.id.class_codename);
mSectionName = (EditText) this.findViewById(R.id.section_name);
mSectionDescription = (EditText) this.findViewById(R.id.section_description);
mAddClass = (Button) this.findViewById(R.id.addclass);
mAddSection = (Button) this.findViewById(R.id.addsection);
mClassList = (ListView) this.findViewById(R.id.classlist);
mSectionList = (ListView) this.findViewById(R.id.sectionlist);
mClassSectionInfoList = (ListView) this.findViewById(R.id.classsectionsinfo);
mClassSelection = (Spinner) this.findViewById(R.id.classselection);
mDBHlpr = new DBHelper(this);
refreshDisplay();
handleButtons();
}
private void handleButtons() {
mAddClass.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if ((mClassName.getText().toString().length() > 0) &&
mClassCode.getText().toString().length() > 0) {
mDBHlpr.addClass(
mClassName.getText().toString(),
mClassCode.getText().toString()
);
refreshDisplay();
}
}
});
mAddSection.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if ((mSectionName.getText().toString().length() > 0) &&
(mSectionDescription.getText().toString().length() > 0)) {
mDBHlpr.addSection(
mSectionName.getText().toString(),
mSectionDescription.getText().toString(),
mClassSelection.getSelectedItemId()
);
refreshDisplay();
}
}
});
}
private void refreshDisplay() {
// Only allow sections to be added if at least one Class exists
if (mDBHlpr.getClassesCount() < 1) {
mSectionName.setVisibility(View.GONE);
mSectionDescription.setVisibility(View.GONE);
mAddSection.setVisibility(View.GONE);
} else {
mSectionName.setVisibility(View.VISIBLE);
mSectionDescription.setVisibility(View.VISIBLE);
mAddSection.setVisibility(View.VISIBLE);
}
// Get Cursors from DB
mClasses = mDBHlpr.getClasses();
mSections = mDBHlpr.getSections();
mCLassSectionInfo = mDBHlpr.getClassAndSectionDetailsCombined();
// Prepare the Classes List Adapter or swap the cursor
if (mSCAClasses == null) {
mSCAClasses = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_1,
mClasses,new String[]{DBHelper.COl_CLASSNAME},
new int[]{android.R.id.text1},
0
);
} else {
mSCAClasses.swapCursor(mClasses);
}
// Prepare the Sections List Adapter
if (mSCASections == null) {
mSCASections = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_1,
mSections,
new String[]{DBHelper.COL_SECTIONNAME},
new int[]{android.R.id.text1},
0
);
} else {
mSCASections.swapCursor(mSections);
}
if (mSCAClassSecInfo == null) {
mSCAClassSecInfo = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_1,
mCLassSectionInfo,
new String[]{DBHelper.COL_COMBINED},
new int[]{android.R.id.text1},
0
);
} else {
mSCAClassSecInfo.swapCursor(mCLassSectionInfo);
}
mClassList.setAdapter(mSCAClasses);
mClassList.setBackgroundColor(0xFF5555ff);
mSectionList.setAdapter(mSCASections);
mSectionList.setBackgroundColor(0xFF55FF55);
mClassSelection.setAdapter(mSCAClasses);
mClassSectionInfoList.setAdapter(mSCAClassSecInfo);
mClassSectionInfoList.setBackgroundColor(0xFFFFFFDD);
}
}