views:

44

answers:

2

I have a sqlite database with three tables: Notes, Lists, and Notes-in-Lists.

Both Notes and Lists have an autogenerated id column and some extra data columns like title. Notes-in-Lists is an association table with an autokey, and two foreign keys that point to a Note id and a List id.

I have a query that returns all notes in a given list:

Select _id, title From Notes
Join Notes_in_Lists On Notes._id=Notes_in_Lists.note_id
Where Notes_in_Lists.list_id=2

This would return all note titles and ids from List 2 for example.

However, notes can be in multiple lists and I need to be able to tell if a note is associated with multiple lists. This is indicated by the same Notes_in_Lists.note_id being listed multiple times in the Notes_in_Lists table.

Easy enough to do by itself:

Select Count(note_id) From Notes_in_Lists Where note_id=2

But I need to combine the two queries above into one query and I have not idea where to begin.

Edit
Sample data

Notes:  
_id title  
1   "Note 1"
2   "Note 2" 
3   "Note 3"   
4   "Note 4" 

Note_in_Lists
_id note_id list_id  
1   1       2  
2   1       3  
3   2       2  
4   3       1   
5   4       2  
6   4       4
7   4       5  

Sample output (query for contents of list 2):

_id  title      numberOfLists
1    "Note 1"   2
2    "Note 2"   1
4    "Note 4"   3
A: 
SELECT n._ID, Title, Count(*) numberOfLists
FROM Notes n, Notes_In_Lists l
where n._id = l.note_id
  AND NOT EXISTS (Select 1 
              from notes_in_lists l2 where 
              l2.note_Id = n._id
              AND l._Id = 2)
group by n._ID, n.Title
Michael Pakhantsov
This will also return Note 3 in the results. I need to exclude notes that are not associated with list 2
CodeFusionMobile
@CodeFusionMobile - I updated query
Michael Pakhantsov
+1  A: 
Select Notes._id, Notes.title, Count(Nil2.list_id)
From Notes
Inner Join Notes_in_Lists NiL1 On Notes._id=NiL1.note_id
Inner Join Notes_in_Lists NiL2 On Notes._id=NiL2.note_id
Where NiL1.list_id=2
Group By Notes._id, Notes.title;

It can seem wasteful to do two joins, but that's what you need to basically run two queries.

MPelletier
Cool. I didn't know you could join to same table twice. I'll try it out
CodeFusionMobile
As for doing two joins, it's needed. I'm working in android, and a flash read to get the database twice for two queries would likely be slower than running a slightly more complex query once.
CodeFusionMobile
Aye, not to mention the hassle of reassembling the results afterwards :)
MPelletier