sql - 带计数的简单 sql 查询

标签 sql sqlite count nested

我正在使用 SQLite。 我需要帮助解决一个简单的问题。 这是我的三个表:

--------------
problem
--------------
id (primary key)
question_id (foreign key)

--------------
question
--------------
id (primary key)
answer_id (foreign key)

--------------
answer
--------------
id (primary key)

我想得到在问题的每个问题中至少有 N 个答案的所有问题。我给你举个例子:

-------
problem
id 
1
2


-------
question 
id   problem_id
1    1
2    1
3    1
4    2

-------
answer
id   question_id
1    1
2    1
3    1
4    2
5    2
6    3
7    4
8    4

如果 n=2,我的结果应该是 Problem_id=2。

我已经尝试过这个:

   select distinct question.problem_id 
   from answer, question
   where answer.question_id = question.id
   group by answer.question_id
   having count(*) >= 2

但它不起作用,因为它会出现至少一个问题且至少有 2 个答案的问题。所有问题都必须满足该条件。

有什么问题吗?

最佳答案

select problem_id
from
(
    select q.problem_id, q.id, count(a.id) answercount
    from question q
    left join answer a on a.question_id = q.id
    group by q.problem_id, q.id
) g
group by problem_id
having min(answercount) >= 2

替代方案(例如 4 个答案)

select distinct q.problem_id
from question q
left join answer a on a.question_id = q.id
left join answer b on b.question_id = q.id and a.id < b.id
left join answer c on c.question_id = q.id and b.id < c.id
left join answer d on d.question_id = q.id and c.id < d.id
where d.id is not null

您可以根据需要扩展此模式。如果您确实需要一个参数化的查询,您可以做一些疯狂的事情,例如连接 6 次,改变 WHERE 子句,如下所示:

where case when f.id is not null then 6
           when e.id is not null then 5
           when d.id is not null then 4
           when c.id is not null then 3
           when b.id is not null then 2
           else 1 end >= {{YourParamHere}}

关于sql - 带计数的简单 sql 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13059892/

相关文章:

SQLite - 根据表b中相关行的计算结果从表a中选择

mysql - 解决方法 : make mysql column name longer than 64 chars

java - Android 中的 SQLite 按日期和时间排序不起作用

mysql - 开始日期及结束日期的 SQL 语句

android - sqlite 中的 strftime() 给出了错误的结果

python - 计算数组中相同的元素并创建字典

c++ - 数组中不同数量的字符串

c# - Linq:确定序列中的项目数是否满足条件

sql - PostgreSQL继承表和插入触发器

sql - 如何执行引用表变量的 SQL 字符串?