Android SQLite query multiple tables
Im trying to do something like this (This is MySQL format)
SELECT q.question_id, q.question, q.answer
FROM relationship r, questions q
WHERE r.cat_id =1
AND r.question_id = q.question_id
LIMIT 0 , 30
So, I got questions stored in one table, then categories in another table. I have the relationship table set up so that a question can be in multiple categories. So say a question has an id of 5, and its开发者_如何转开发 in 3 different categories, the relationship table would look like this
relation_id, question_id, category_id
1 5 1
2 5 2
3 5 3
4 6 1
So, say I wanna get all the questions with the cat_id of 1, I should get 2 results. That's basically what I'm trying to do.
If you want all questions with cat_id
of 1, then you want this:
select q.question, q.answer
from questions q
join relationship r on q.question_id = r.question_id
where r.cat_id = 1
I've switch to the ANSI join syntax rather than implied join conditions in the WHERE clause because the explicit version helps to avoid certain types of errors; in particular, ANSI joins help avoid accidental cross products and that's what your "MySQL format" query has because you neglected to include a join condition for category
. That accidental cross product is almost certainly the source of your "returns each item 3 times" problem.
SELECT q.question, q.answer
FROM questions q
left join category c on q.catID = c.catID
left join relationship r on q.relID = r.relID
Some thing like this will de the trick
精彩评论