How to distribute duplicate rows in MySQL output?
P粉805107717
P粉805107717 2023-09-13 15:45:37
0
1
619

I have a MySQL query that outputs rows in random order.

Each row has a name column, and sometimes queries may produce duplicate rows (name rows with the same value) - this is by design. < /p>

However, sometimes queries can accidentally group duplicate rows directly together in the output.

I'm trying to find a way to evenly distribute rows with duplicate names in the output so that duplicate rows don't accidentally get grouped together.

P粉805107717
P粉805107717

reply all(1)
P粉311423594

One way to achieve this is to modify the MySQL query to include additional sorting criteria to ensure that rows with the same name are evenly distributed throughout the output.

Here is a sample query to accomplish this:

SELECT * FROM my_table ORDER BY name, RAND();

This query sorts the rows first by name and then by a random value generated by the RAND() function. Random values ​​ensure that rows with the same name are randomly distributed throughout the output, rather than grouped together.

Note that using the RAND() function in an ORDER BY clause can be computationally expensive and may not scale well with large tables. If this is the case, you might consider using a different deterministic function (such as an MD5 hash of the name) to achieve similar results.

SELECT * FROM my_table ORDER BY MD5(name), RAND();

This query first sorts the rows by the MD5 hash of the name, and then sorts the rows by a random value generated by the RAND() function. The MD5 hash ensures that rows with the same name are evenly distributed throughout the output, while the random value ensures that the order of rows is random.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template