Limit occurrences of column

Discussion in 'MySQL' started by Thorlax402, Feb 28, 2013.

  1. #1
    I'm having a little bit of trouble writing a query, and I was hoping someone could help me out. I'm trying to query the number of entries in a database while limiting the number of duplicates in a column to x.


    | a_id | important |
    ---------------------------
    | 0001 |      'a' |
    | 0002 |      'b' |
    | 0003 |      'c' |
    | 0004 |      'a' |
    | 0005 |      'a' |
    | 0006 |      'a' |
    | 0007 |      'b' |
    | 0008 |      'b' |
    Code (markup):
    In the table above, let's say I want to limit the query to yield only all rows such that there are no more than 2 duplicates amongst the column "important".

    Results:

    | a_id | important |
    ---------------------------
    | 0001 |      'a' |
    | 0002 |      'b' |
    | 0003 |      'c' |
    | 0004 |      'a' |
    | 0007 |      'b' |
    Code (markup):
    Is this query even possible?


    Thanks in advance!
     
    Thorlax402, Feb 28, 2013 IP
  2. jestep

    jestep Prominent Member

    Messages:
    3,659
    Likes Received:
    215
    Best Answers:
    19
    Trophy Points:
    330
    #2
    You could limit it to 1 using a GROUP BY in the query. I can't think of a way to limit it to 2 of one type through.
     
    jestep, Mar 5, 2013 IP
  3. gandalf117

    gandalf117 Active Member

    Messages:
    111
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    53
    #3
    What you are trying to do turned out to be really hard though not impossible. You are basically trying to limit the result of the group by clause to 2 instead of the unique 1. And not just any 2 but the top 2.

    If you really want to do this in one quiz maybe something like this can work (assuming X is 2):


    SELECT
    important, a_id
    FROM (
    SELECT
    *,
    @im := CASE WHEN @prev_important = important THEN @im + 1 ELSE 1 END AS im,
    @prev_important := important
    FROM tableName AS T1, (SELECT @prev_important := '', @im := 0) AS vars
    ORDER BY important, a_id ASC
    ) AS T2
    WHERE im <= 2
    ORDER BY important, a_id ASC
     
    gandalf117, Mar 25, 2013 IP