L
L
Lander2016-01-27 11:55:05
MySQL
Lander, 2016-01-27 11:55:05

How to make a tricky selection from the database?

Good afternoon.
Interested in such a question, let's say there is a table:
id | type | name
1 | one | The first element is one
2 | one | The second element is one
3 | one | The third element is one
4 | two | The first element is two
5 | two | The second element is two
6 | two | The third element is two
7 | two | The fourth element is two
...
I would like to pull out one RANDOM line from each type with one request. My games with GROUP BY and ORDER BY RAND() resulted in only the first rows for each type being pulled out, but the types are output in random order. Googling didn't lead to anything. The task is further complicated by the fact that it is not known in advance how many types there are.
Thanks in advance to all who answer.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
C
Cat Anton, 2016-01-27
@usdglander

SELECT * FROM (
    SELECT * FROM elements ORDER BY RAND()
) e GROUP BY e.type;

N
Nikita Fedotov, 2016-02-02
@ColorCast

I had a task related to crypto-protection, I had to write my own random , because the existing function has a decent accuracy.
The essence of the algorithm is based on getting a list of record IDs and another column for a fixed length hash. Next, a random hash is generated and compared by weight match with the hashes of the control records. There are hashes with the same weights. For them, we again generate an arbitrary hash and compare. So until there is only one value left. Further we receive record on ID.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question