SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Member
    Join Date
    Aug 2006
    Posts
    2
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Question COUNT() optimisation, moderately large dataset

    Hi folks

    A website I am working with has grown fairly large and we're starting to take a hit from my (admittedly) fairly novice SQL queries.

    I have an hourly cron job which calculates the number of views which an article has received. I have over 10000 articles and for compatibility with my predecessor's code, we have a 10 million row "views" table.

    We're trying to tweak this query:
    Code SQL:
    UPDATE `articles` a 
    SET a.views = a.views + ( 
    SELECT COUNT( apv.id ) FROM `article_pages` ap 
    LEFT JOIN `article_page_views` apv ON page_id = ap.id 
    WHERE ap.article_id = a.id AND apv.created > 1277878382
    )

    I would like it to only update articles for which there are actually new page views. I am doing this the wrong way round though, because it updates every article in the database (whether they have a new view or not) -- just not sure how to fix it!

    Thanks in advance for your assistance!

  2. #2
    SQL Consultant gold trophysilver trophybronze trophy
    r937's Avatar
    Join Date
    Jul 2002
    Location
    Toronto, Canada
    Posts
    39,341
    Mentioned
    63 Post(s)
    Tagged
    3 Thread(s)
    try this --
    Code:
    UPDATE articles AS a 
    INNER
      JOIN article_pages AS ap
        ON ap.article_id = a.id
    INNER
      JOIN ( SELECT page_id
                  , COUNT(*) AS views
               FROM article_page_views 
              WHERE created > 1277878382
             GROUP
                 BY page_id ) AS apv
        ON apv.page_id = ap.id 
       SET a.views = a.views + apv.views
    rudy.ca | @rudydotca
    Buy my SitePoint book: Simply SQL
    "giving out my real stuffs"

  3. #3
    SitePoint Member
    Join Date
    Aug 2006
    Posts
    2
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    You're a star! I'll take a look at the manual to try and figure out *why* that works, but that'll get me going. Thank-you.


Bookmarks

Posting Permissions

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