tags:

views:

22

answers:

2

Say I have the following data:

|bookID|data|
|1|a|
|1|b|
|1|c|
|2|x|
|2|y|
|3|t|

I want to select all the books that have at least X rows. So if X=3 then I'd only get all the rows with bookID=1. If X=2 then I'd only get all the rows with bookID=1 or bookID=2, etc.

Can I do this with SQLite3?

+2  A: 

This example will get all books that have 3 or more rows.

  SELECT * FROM Books WHERE BookID IN
     (SELECT BookID FROM Books GROUP BY BookID HAVING COUNT(*) >= 3)
Larry Lustig
@Larry, This doesn't seem to work.
slomojo
I don't have SQLite on this computer to test it, but it should work. What results do you see?
Larry Lustig
1,a (newline) 1,b (newline) 1,c (newline) --- wierd eh!
slomojo
That is the correct response to the OP's question.
Larry Lustig
+1 ... Oops, I misunderstood the question.
slomojo
A: 

Here is a way to do it by JOINing a subquery:

SELECT bookID FROM books
    JOIN (SELECT COUNT(*) AS book_count,bookID FROM books GROUP BY bookID)
        USING (bookID)
    WHERE book_count >= 2
    GROUP BY bookID

Larry Lustig’s answer is much less verbose (and probably faster, too).

Chris Johnsen
I wish I could mark both answers as correct. Larry Lustig's most certainly works, however, it is limited to only having a single index. This solution allows you to have multiple indexes and I ended up having to use this one for another, similar, problem.
baubie