If this is your first visit, be sure to check out the FAQ by clicking the link above. You may have to register before you can post: click the register link above to proceed. To start viewing messages, select the forum that you want to visit from the selection below.

 
Go Back  dBforums > Database Server Software > MySQL > Updating a field in every row?

Reply
 
LinkBack Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old 02-02-12, 12:22
farzher farzher is offline
Registered User
 
Join Date: Feb 2012
Posts: 2
Updating a field in every row?

Hey, I want to update popularity(int) field in every email_data row, and set it equal to some formula of how many votes it has, how old it is, etc.

This is what I have so far:

Code:
UPDATE email_data SET popularity = 

(SELECT (SUM(up) - SUM(down)*2)
FROM rating WHERE email_data_id=email_data.id)
+
(SELECT -DATEDIFF(CURDATE(), email_data.timestamp))
But this only works on a few rows, because if the email_data was never "rated" it won't have a row in the 'rating' table and will be skipped, I'd like it to just have a value of 0 in that case. Can anyone help me out on how to set up this query?

Last edited by farzher; 02-02-12 at 12:35. Reason: typos
Reply With Quote
  #2 (permalink)  
Old 02-02-12, 13:51
r937 r937 is offline
SQL Consultant
 
Join Date: Apr 2002
Location: Toronto, Canada
Posts: 19,525
Code:
UPDATE email_data 
LEFT OUTER
  JOIN ( SELECT email_data_id
              , SUM(up) AS sum_up
              , SUM(down) AS sum_down
           FROM rating
         GROUP
             BY email_data_id ) AS r
    ON r.email_data_id = email_data.id
   SET email_data.popularity = 
       CASE WHEN r.email_data_id IS NULL
            THEN 0
            ELSE r.sum_up - r.sum_down*2
               - DATEDIFF( CURDATE(), email_data.timestamp )
        END
__________________
r937.com | rudy.ca
please visit Simply SQL and buy my book
Reply With Quote
  #3 (permalink)  
Old 02-02-12, 15:22
farzher farzher is offline
Registered User
 
Join Date: Feb 2012
Posts: 2
I can't believe you even understood the question.

Thanks, this works perfectly.
Reply With Quote
Reply

Tags
formula, popularity, rating, update

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On