通过sqlite3选择列中至少有X行和某些值的行?

时间:2010-10-19 21:29:42

标签: sqlite

说我有以下数据:

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

我想选择所有至少有X行的书籍。所以如果X = 3那么我只得到bookID = 1的所有行。如果X = 2那么我只得到bookID = 1或bookID = 2等所有行。

我可以使用SQLite3吗?

2 个答案:

答案 0 :(得分:2)

此示例将获取包含3行或更多行的所有图书。

  SELECT * FROM Books WHERE BookID IN
     (SELECT BookID FROM Books GROUP BY BookID HAVING COUNT(*) >= 3)

答案 1 :(得分:0)

这是通过加入子查询来实现的:

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更加冗长(也可能更快)。