【问题标题】:SQL query - select max where a count greater than valueSQL查询 - 选择最大值,其中计数大于值
【发布时间】:2014-04-22 19:58:14
【问题描述】:

我有两张表,结构如下:

问题表

id int, 
question text, 
answer text, 
level int

进度表

qid int, 
attempts int, 
completed boolean (qid means question id)

现在我的问题是如何构建一个查询来选择正确问题的数量大于 30 个的最大级别。

我创建了这个查询,但它不起作用,我不知道为什么。

SELECT MAX(Questions.level) 
FROM Questions, Progress 
WHERE Questions.id = Progress.qid AND Progress.completed = 1 
GROUP BY  Questions.id, Questions.level 
Having COUNT(*) >= 30

我想在一个查询中使用它,因为我怀疑这是可能的,并且可能是查询它的最“优化”方式。感谢您的帮助!

【问题讨论】:

    标签: mysql sql count


    【解决方案1】:

    这种结构会起作用。你可以弄清楚细节。

    select max(something) maxvalue
    from SomeTables
    join (select id, count(*) records
    from ATable
    group by id) temp on ATable.id = temp.id
    where records >= 30
    

    【讨论】:

    • 是否需要加入?你不能通过 HAVING 和 GROUP BY 得到结果吗?
    【解决方案2】:

    一步一步做,而不是把两个表连接起来。在内部选择中找到正确回答 30 次的问题(即问题 ID)。在一个外层select中找到对应的levels,取最大值:

    select max(level) 
    from questions
    where id in
    (
      select qid
      from progress 
      where completed = 1
      group by qid
      having count(*) >= 30
    );
    

    【讨论】:

      猜你喜欢
      • 2012-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-26
      • 2015-02-03
      • 2022-10-13
      • 2018-09-07
      • 1970-01-01
      相关资源
      最近更新 更多