简体   繁体   中英

Random row with group by?

I try to display a random row of each group with SQL and PHP. A group is a "category" in my database.

I use this:

SELECT * 
FROM images i, set s
WHERE i.ImageSetId = s.SetId
GROUP BY s.SetCategorie
ORDER BY rand()

With this code, I've got one row for each category but it always return the first row and I don't understand how to display a random row for each categorie. Can someone help me, please ?

ps: I've tried other things with date, and GROUP BY rand('e.SetCategorie') but it's don't work at all.

Thanks in advance and excuse my english :p

You need filtering rather than aggregation.

In MySQL 8.0, you can use window functions:

SELECT *
FROM (
    SELECT 
        i.*, 
        s.*,
        row_number() over(partition by s. SetCategorie Order by rand()) rn
    FROM images i
    INNER JOIN set s ON i.ImageSetId = s.SetId
) t
WHERE rn = 1

In earlier versions, it is much more complicated. Here is a hacky solution using a partial group by :

SELECT *
FROM (
    SELECT 
        i.*, 
        s.*
    FROM images i
    INNER JOIN set s ON i.ImageSetId = s.SetId
    ORDER BY RAND()
) t
GROUP BY SetCategorie

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