Mysql group queries the first 10 pieces of data in each group.

section:
section

article:
article

the requirement is to query out all the fields of the forum at once, and the first 10 articles belonging to this section (field id,title,content is fine). The sid in article corresponds to the id in section

.
Mar.06,2021

you can do this:

SELECT *, result.row_number
FROM
  (SELECT *, (@num:=IF(@group = `sid`, @num +1, IF(@group := `sid`, 1, 1))) row_number
    FROM article
    ORDER BY sid) result
WHERE row_number <= 10
;
The

article table is sorted by sid, and then one row_number, per row is calculated as shown above.

I hope I can help you.


I follow your operation, the first query will query all the data. The second query got the expected results.
first query result:
.png
:
.png

the number of results of the two queries is inconsistent. The row_number of the first query is 1, and the second query is the correct result. I don't know why this happened. Is there anyone who can answer it?

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b3a417-345c7.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b3a417-345c7.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?