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

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.

I would generate a row number increment partitioned by difficulty (i.e. it starts 1 for each difficulty type) and filter by the number you want with that.