2
votes

hi i have a little bit confusion about this SQL Query in Android with SQlite

i have 3 simple tables table category

   |_id|name| 
   |1  |cat1
   |2  |cat2
   |3  |cat3
   |4  |cat4

table list

   |_id|name| 
   |1  |list1
   |2  |list2
   |3  |list3
   |4  |list4

and i have other table which contains the id s for previous tables

|_id|category|list   |name
| 1 |2       |1      |item1
| 2 |1       |2      |item2
| 3 |2       |3      |item3
| 4 |2       |1      |item4

i want to left join the cat table so that is always shown as cat1 (count 10) cat2 (count 2) cat3 (count 3) cat4 (count 4)

when i filter with where list = 1 then the category doesn show the null columns

any suggestions

1

1 Answers

0
votes

You could use a subquery:

SELECT category.name as cat, B.catcount as catcount
FROM category LEFT JOIN (SELECT table3.category, count(*) AS catcount
FROM table3
WHERE table3.list=1
GROUP BY table3.category) as B ON category.[_id] = B.category;

Should give an output like:

|cat  |catcount|
|cat1 |    null|
|cat2 |       2|
|cat3 |    null|
|cat4 |    null|