如何将sql请求分成两部分(挑战)

我有下面的代码。本质上,它从数据库中获取数学问题并将其列出以供用户回答。有两个部分:mathcalc 和 mathnocalc。现在,程序随机输出它们。

有时可能有 15 个 mathcalc 而只有 5 个 mathnocalc。这对我来说是个问题。我需要能够指定程序应该只输出 10 mathcalc 和 10 mathnocalc。

此外,我希望能够分割输出,以便第一页只是mathcalc(它可以超过一页。我只需要先打印出所有 mathnocalc 然后打印出所有 mathcalc 之后。本质上是两个组)。

我想知道如何将其与现有代码合并。这绝对是具有挑战性的,但我想知道是否有人能够帮助我。


倚天杖
浏览 87回答 1
1回答

繁星淼淼

基本上,我们使用 2 个SELECT语句并将UNION它们组合成一个结果集。SELECT question, type, Topic, Skill, imagename, answerA, answerB, answerC, answerD, correctanswer FROM goodquestions WHERE type = 'mathnocalc' ORDER BY RAND() LIMIT 0,10上面的查询将返回 10 个 mathnocalc 类型的随机行。您一定会确信这一点。我将上述查询用作与另一个查询的 UNION 的嵌套查询。SELECT * FROM (SELECT question, type, Topic, Skill, imagename, answerA, answerB, answerC, answerD, correctanswer FROM goodquestions WHERE type = 'mathnocalc' ORDER BY RAND() LIMIT 0,10) as cat1UNIONSELECT * FROM (SELECT question, type, Topic, Skill, imagename, answerA, answerB, answerC, answerD, correctanswer FROM goodquestions WHERE type = 'mathcalc' ORDER BY RAND() LIMIT 0,10) as cat2尝试上面的查询并让我知道结果。要根据类别显示结果,您可以简单地将查询分为两部分:逻辑示例:$queryNoCalc = 'SELECT question, type, Topic, Skill, imagename, answerA, answerB, answerC, answerD, correctanswer FROM goodquestions WHERE type = 'mathnocalc' ORDER BY RAND() LIMIT 0,10';$noCalcResult variable will store the result set of above query.Similarly,$queryCalc = 'SELECT question, type, Topic, Skill, imagename, answerA, answerB, answerC, answerD, correctanswer FROM goodquestions WHERE type = 'mathcalc' ORDER BY RAND() LIMIT 0,10';$calcResult variable will store the result set of above query.现在,您可以在不同的 DIV 中使用单独的结果。<div class="no-calc">&nbsp; <h3>NO CALULATOR ALLOWED</h3>&nbsp; while ($noCalcResult):&nbsp; &nbsp; Do the stuff;&nbsp; endwhile;</div><div class="calc">&nbsp; <h3>CALULATOR ALLOWED</h3>&nbsp; while ($queryCalc):&nbsp; &nbsp; Do the stuff;&nbsp; endwhile;</div>希望你能理解这个概念。
打开App,查看更多内容
随时随地看视频慕课网APP