简体   繁体   中英

Take random row for GROUP BY

I need one row for each textid . But it has to be chosen random, not the first in the MySQL table.

Shuffling like this does not work. It still takes the first row.

SELECT * FROM (
  SELECT * FROM textelements ORDER BY rand()
) AS z
GROUP BY z.textid;

Read the comments for my solution. I added LIMIT 1000000 to the subquery.

WITH cte AS ( 
    SELECT *, 
           ROW_NUMBER() OVER (PARTITION BY textid ORDER BY RAND()) rn
    FROM textelements 
)
SELECT *
FROM cte
WHERE rn = 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM