Results 1 to 5 of 5
  1. #1
    Join Date
    May 2009
    Posts
    10

    Unanswered: Returning Top N elements

    Hi,

    I have a db that stores searches. I want to return top N searches.
    Currently it stores like...

    Keyword
    --------
    A
    A
    C
    B
    C
    A

    I want to return it like...

    Top
    ----
    A
    C
    B

    Can you please help me with the query?
    Thanks.

  2. #2
    Join Date
    Apr 2002
    Location
    Toronto, Canada
    Posts
    20,002
    Code:
    SELECT keyword AS Top
      FROM daTable
    GROUP
        BY keyword
    ORDER
        BY COUNT(*) DESC LIMIT N
    rudy.ca | @rudydotca
    Buy my SitePoint book: Simply SQL

  3. #3
    Join Date
    May 2009
    Posts
    10
    Yummy!
    Thanks.

  4. #4
    Join Date
    May 2009
    Posts
    10
    A little change...

    Instead of storing each keyword, I am going to check if keyword is already in table, if yes then increase it's "repeat" column by 1 or else add it to db with "repeat" as 1.

    Is it possible with MySQL or do I have to do it in lang?

  5. #5
    Join Date
    Apr 2002
    Location
    Toronto, Canada
    Posts
    20,002
    yes, it's possible

    use INSERT... ON DUPLICATE KEY UPDATE ...

    rudy.ca | @rudydotca
    Buy my SitePoint book: Simply SQL

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •