Combine 4 SELECT queries in mysql

I am trying to combine these 3 mysql statements. I use UNION and JOIN Keyword, but it is not suitable for the output that I wanted. Any suggestions? These are my 3 statements.

SELECT * FROM entrancequestion
WHERE Subject='Abstract Reasoning'
ORDER BY RAND()
LIMIT 10

SELECT * FROM entrancequestion
WHERE Subject='English'
ORDER BY RAND()
LIMIT 30

SELECT * FROM entrancequestion
WHERE Subject='Mathematics'
ORDER BY RAND()
LIMIT 30

SELECT * FROM entrancequestion
WHERE Subject='Science'
ORDER BY RAND()
LIMIT 30

I tried to combine the first two operators like this:

SELECT * FROM entrancequestion
WHERE Subject='Abstract Reasoning'
LIMIT 10
UNION
SELECT * FROM entrancequestion
WHERE Subject='English'
ORDER BY RAND()
LIMIT 30;

however, it only reads the second LIMIT request, in which t prints only 30 lines.

I would like to create a query that displays a total of 100 rows and is randomized according to the index. Your help would be greatly appreciated.

+4
source share
4 answers

Quoting docs ,

ORDER BY LIMIT SELECT, , SELECT:

(SELECT * FROM entrancequestion
WHERE Subject='Abstract Reasoning'
ORDER BY RAND()
LIMIT 10)

UNION

(SELECT * FROM entrancequestion
WHERE Subject='English'
ORDER BY RAND()
LIMIT 30)

UNION

(SELECT * FROM entrancequestion
WHERE Subject='Mathematics'
ORDER BY RAND()
LIMIT 30)

UNION

(SELECT * FROM entrancequestion
WHERE Subject='Science'
ORDER BY RAND()
LIMIT 30 )
+3

UNION LIMIT, :

(SELECT * FROM entrancequestion WHERE Subject='Abstract Reasoning' LIMIT 10)
UNION
(SELECT * FROM entrancequestion WHERE Subject='English' ORDER BY RAND() LIMIT 30);
+3

Try the following:

 SELECT TOP 10 * FROM entrancequestion
 WHERE Subject='Abstract Reasoning'
 UNION
 SELECT TOP 30 * FROM entrancequestion
 WHERE Subject='English'
 ORDER BY RAND()
0
source

If you do not care about the first one that has LIMIT 10:

SELECT * FROM entrancequestion
WHERE
    Subject='Abstract Reasoning' OR
    Subject='English' OR
    Subject='Mathematics' OR
    Subject='Science'
ORDER BY RAND()
LIMIT 30
0
source

Source: https://habr.com/ru/post/1530612/


All Articles