简体   繁体   中英

How to combine 3 sql query from same table

I want to generate 12 random questions from database which consist 4 easy, 4 medium and 4 hard questions. Also the questions must not repeated

This is my code:

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()

This code still got error.

You need to enclose each query between parentheses, like so :

(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() 

Learn how to debug. Does this query return any rows?

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

I'm guessing not. That would leave three possibilities:

  • The specified user has answered all questions/all the easy questions.
  • No questions have difficulty of 'easy' .
  • The NOT IN fails.

If I were a betting man, I would guess the last. NOT IN never returns true when any of the values in the value list are NULL . Learn to use NOT EXISTS instead.

So try this:

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;

A separate issue is munging the query string with the user id. Learn to use parameters as well.

我将生成按难度划分的行号增量(即,每种难度类型均以1开始)并按所需的数字进行过滤。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM