Count efficiency vs storing a total

Discussion in 'MySQL' started by Silver89, Jul 28, 2011.

  1. #1
    If using Innodb tables with properly optimized indexes and foreign keys, two of my tables are `user` and photo.

    (for example)

    In `user` I have - id, username, photoCount
    Then in `photo` I have - id, fileContents, userId

    Everytime a photo is inserted into `photo` a query is also run the `user` table to do photoCount = photoCount+1

    Does it make more sense to keep it like this and just do:

    SELECT `user`.username, `photo`.photoCount 
    FROM `user` 
    INNER JOIN `picture` ON `user`.id = `picture`.`userId` 
    WHERE `user`.id='1' 
    Code (markup):
    OR remove photoCount and just do it dynamically with a count query?

    SELECT `user`.username, COUNT(`picture`.id) 
    FROM `user` 
    INNER JOIN `picture` ON `user`.id = `picture`.`userId` 
    WHERE `user`.id='1' 
    Code (markup):
     
    Silver89, Jul 28, 2011 IP
  2. plog

    plog Peon

    Messages:
    298
    Likes Received:
    11
    Best Answers:
    1
    Trophy Points:
    0
    #2
    It depends. How often are you retrieving the count of photos? How large are you tables?

    Theoretically the correct way is to do it dynamically with a count query, however in the real world there are exceptions and this may just be one of those times.
     
    plog, Jul 28, 2011 IP
  3. srikanth03565

    srikanth03565 Greenhorn

    Messages:
    5
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    11
    #3
    If you have large data best part is saving count in your use table if you don't have that large data use count statement
     
    srikanth03565, Aug 7, 2011 IP
  4. mwasif

    mwasif Active Member

    Messages:
    816
    Likes Received:
    23
    Best Answers:
    1
    Trophy Points:
    70
    #4
    Saving the photo count is the way to go. It is really fast when your database grows.

    The correct query will be (modified your first query)
    SELECT username, photoCount  FROM `user` WHERE id='1'
    Code (markup):
    Remember to do photoCount-1 when a use deletes a picture.
     
    mwasif, Aug 7, 2011 IP
  5. le_punk

    le_punk Peon

    Messages:
    31
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #5
    i agree, saving the count is the way to go, however...

    i have a medium sized social network where i used a little trick. i stored the users photos on the server in the /photos/USERID/ and when i needed the count I just counted the files in that directory. fast and you don't have to store any metadata
     
    le_punk, Aug 26, 2011 IP