如何结合同一个表中的3个sql查询

时间:2017-09-18 13:31:21

标签: php sql database

我想从数据库生成12个随机问题,包括4个简单,4个中等和4个难题。问题也不能重复

这是我的代码:

SELECT * FROM chapter1
WHERE question_id NOT IN (SELECT question_id FROM 
                          chapter1_useranswer WHERE username = '$usernow') 
  AND (difficulty = 'easy')
LIMIT 4
UNION ALL
SELECT * FROM chapter1
WHERE question_id NOT IN (SELECT question_id FROM 
                          chapter1_useranswer WHERE username = '$usernow') 
AND (difficulty = 'medium')
LIMIT 4
UNION ALL
SELECT * FROM chapter1
WHERE question_id NOT IN (SELECT question_id FROM 
                          chapter1_useranswer WHERE username = '$usernow') 
AND (difficulty = 'hard')
LIMIT 4
ORDER BY RAND()

此代码仍然出错。

3 个答案:

答案 0 :(得分:1)

您需要将每个查询括在括号中,如下所示:

(SELECT * 
 FROM   chapter1 
 WHERE  question_id NOT IN (SELECT question_id 
                            FROM   chapter1_useranswer 
                            WHERE  username = '$usernow') 
        AND ( difficulty = 'easy' ) 
 LIMIT  4) 
UNION ALL 
(SELECT * 
 FROM   chapter1 
 WHERE  question_id NOT IN (SELECT question_id 
                            FROM   chapter1_useranswer 
                            WHERE  username = '$usernow') 
        AND ( difficulty = 'medium' ) 
 LIMIT  4) 
UNION ALL 
(SELECT * 
 FROM   chapter1 
 WHERE  question_id NOT IN (SELECT question_id 
                            FROM   chapter1_useranswer 
                            WHERE  username = '$usernow') 
        AND ( difficulty = 'hard' ) 
 LIMIT  4) 
ORDER  BY Rand() 

答案 1 :(得分:1)

了解如何调试。此查询是否返回任何行?

SELECT *
FROM chapter1
WHERE question_id NOT IN (SELECT question_id FROM 
chapter1_useranswer WHERE username = '$usernow'
                         ) AND
      difficulty = 'easy'
LIMIT 4;

我不猜。这将留下三种可能性:

  • 指定用户已回答所有问题/所有简单问题。
  • difficulty没有问题'easy'
  • NOT IN失败。

如果我是一个博彩人,我会猜到最后一个。当值列表中的任何值为NOT IN时,NULL永远不会返回true。请学习使用NOT EXISTS

所以试试这个:

SELECT c.*
FROM chapter1 c
WHERE NOT EXISTS (SELECT 1
                  FROM chapter1_useranswer
                  WHERE username = '$usernow' AND ua.question_id = c.question_id
                 ) AND
      c.difficulty = 'easy'
LIMIT 4;

另一个问题是使用用户ID复制查询字符串。学习如何使用参数。

答案 2 :(得分:0)

我会生成一个按难度划分的行号增量(即每个难度类型都会开始1)并按照你想要的数字过滤。