简体   繁体   中英

Select rows where top n values of a certain column are distinct

I wonder if it's possible to do this in MySQL in a simple and effective way. What I want to do in my example is:

I have a table where I store blog text with a FK to other blog information (title, user etc). The blog text can be stored over several rows (if it's a really long text). Every row has a sequence number to know the order of the text, if there are multiple rows.

Is there any simple way for me to, with one query, select rows starting from the highest FK number (postid) (which will also be the latest added), and set the limit of the response to 10 distinct FK values. To be clear, I don't want to set the limit of the amount of rows to 10, only the limit of distinct postid values.

For example, if I have the following table:

+----------+--------+-----------+
| sequence | postid |   text    |
+----------+--------+-----------+
|    1     |   50   | 'Bla bla' |
|    1     |   51   | 'Bla bla' |
|    1     |   52   | 'Bla bla' | (1)  <-- From here (52 to 61 is 10 different postids)
|    2     |   52   | 'Bla bla' | (2)
|    1     |   53   | 'Bla bla' | (3)
|    2     |   53   | 'Bla bla' | (4)
|    1     |   54   | 'Bla bla' | (5)
|    1     |   54   | 'Bla bla' | (6)
|    1     |   56   | 'Bla bla' | (7)
|    1     |   57   | 'Bla bla' | (8)
|    1     |   58   | 'Bla bla' | (9)
|    1     |   59   | 'Bla bla' | (10)
|    1     |   60   | 'Bla bla' | (11)
|    1     |   61   | 'Bla bla' | (12)  <-- To here
+----------+--------+-----------+

Here I want the bottom 12 rows, since their postid goes from 61 to and including 52, which is 10. The number in parentheses is just for clarification to show how many rows I want to pick.

I hope this is not all too confusing :) So is there any simple and effective way to do this?

SELECT * 
FROM mytable a 
INNER JOIN  ( SELECT DISTINCT(postid) postid 
              FROM mytable  
              ORDER BY postid DESC LIMIT 10) b  
ON a.postid = b.postid

In the following query I INNER JOIN your main table to a temporary table which obtains the (up to) 10 highest postid values. This allows you to retain only records in your original table which have one of the 10 highest postid values. The records you don't want are filtered out since they will not match to anything in the temporary table.

SELECT t1.sequence, t1.postid, t1.text
FROM table t1 INNER JOIN
(
    SELECT DISTINCT postid
    FROM table
    ORDER BY postid DESC
    LIMIT 10
) t2
ON t1.postid = t2.postid

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