Solution 1 :
You can get fields from both fields with tables’ join.
Try to change your query to:
SELECT * FROM SubjectComment LEFT JOIN Student ON SubjectComment.uploadedBy = Student.id WHERE subjectQuestionId = $subjectQuestionId
As a result you’ll get fields from both tables.
You can specify what fields you want to get explicitly:
SELECT sub.*,Student.name FROM SubjectComment as sub LEFT JOIN Student ON sub.uploadedBy = Student.id WHERE subjectQuestionId = $subjectQuestionId
If “uploadedBy” – is a Foreign Key (so it cannot be empty), you can in your query replace “Left Join” with “Inner Join”
Problem :
cursor = db.rawQuery("SELECT * FROM SubjectComment WHERE subjectQuestionId = $subjectQuestionId", null)
cursor.use {
while (it.moveToNext()) {
with(cursor) {
var subjectComment = SubjectComment()
subjectComment.commentId = getLong(0).toInt()
subjectComment.subjectQuestionId = getLong(1).toInt()
subjectComment.comment = getString(2)
subjectComment.uploadedBy = getLong(3).toInt()
subjectComment.dateCreated = getString(4)
subjectCommentList.add(subjectComment)
}
}
}
So this is my code. In this query, I retrieve comments on a question with a RecyclerView and add it into a subjectCommentList
so that I can display all the comments. However, I have an "uploadedBy"
column which contains an Int ID
of a Student
table. I would want to retrieve the Name
from the Student
table with this ID
, but how do I go around doing that? I’ve tried using another cursor inside with(cursor { }
but it didn’t work. Thank you.
Comments
Comment posted by sergiy tikhonov
Cursor holds all columns that are present in your query (that is true both for simple queries and for tables’ joins), the cursor columns’ names are equal to fields’ names in your query (or their aliases). But to get some value from cursor it is better not to use fixed column’s numbers, like