2

this is my table

id | question | 

id's are grouped as

1000 -> 1050
2000 -> 2030
3000 -> 3099
4000 -> 4500
5000 -> 5010

I have to extract 5 records and one for each group of id.

How can I perform this with only one query?

Thanks a lot.

CBroe
  • 91,630
  • 14
  • 92
  • 150
michele
  • 26,348
  • 30
  • 111
  • 168

3 Answers3

0
SELECT f1, f2, ... FROM tablename WHERE id BETWEEN 1000 AND 1050 ORDER BY RAND() LIMIT 1
UNION
SELECTS f1, f2, ... FROM tablename WHERE id BETWEEN 2000 AND 2030 ORDER BY RAND() LIMIT 1
UNION
SELECTS f1, f2, ... FROM tablename WHERE id BETWEEN 2000 AND 2030 ORDER BY RAND() LIMIT 1

and two more selects with UNION

Nedret Recep
  • 726
  • 5
  • 8
0
SELECT *, IF (id > 1000 AND id < 1050, 1, 
          IF (id > 2000 AND id < 2030, 2,
          IF (id > 3000 AND id < 3099, 3,
          IF (id > 4000 AND id < 4500, 4,
          IF (id > 5000 AND id < 5010, 5, 0))))) AS param 
FROM questions WHERE param > 0 GROUP BY param
dikirill
  • 1,873
  • 1
  • 19
  • 21
0

To do this with just one query (without using UNION as was suggested by NedretRecap), you can add group_id (or similar column) to your table and use simple ... GROUP BY group_id.

Assuming that the reserved group size is always the same (it's not possible that some groups will start at +1000 from previous, and other at +300) you could probably use this simple hack:

SELECT id
FROM table
GROUP BY FLOOR(id/1000)

Working example here.

Community
  • 1
  • 1
Vyktor
  • 20,559
  • 6
  • 64
  • 96