How to get photo of the day?
I have two tables in MySQL database:
photos:
PID - PhotoID [PK],
DateOf - DateTime of uploading,
UID -UserID (owner of the photo)
ratings:
WhoUID - UserID who rated,
DateOf - DateTime of rate,
RatingValue - +1 or -1 (positive or negative),
RatingStrength - coefficient (different for each user who vote)
PID - PhotoID, [FK]
Real rating value = RatingValue * RatingStrength
What are possibilities to get "Photo of the day"?
Rules, for example:
- photo of the day must be on site at least 24 hours (since uploaded time)
- photo of the day must have at least 10 votes
- photo of the day is the photo with maximum
Real rating value
in 24 hours since uploaded time - new photo of the day must not be already in
photo_of_day
table
UPD1.
10 votes means - at least 10 records in table ratings
for each photo
UPD2. Is it possible to get 'photo of the day' for exact datetime? For exampl开发者_高级运维e, how can I get photo of the day for '2011-03-11', or '2011-01-25' ?
select p.PID from photos p, ratings r where
r.PID = p.PID and ; Link ratings to photo
p.DateOf >= '$day' and p.DateOf <= '$day' and ; Get the photos uploaded on the specified date
datediff(p.DateOf, now()) > 1 and ; photo of the day must be on site at least 24 hours
count(r.*) >= 10 and ; photo should have at least 10 ratings
not exists(select p.PID from photo_of_day) ; photo should not appear in photo_of_day
group by p.PID ; group the results by PID
order by sum(r.RatingValue*r.RatingStrength) desc ; order descending by RealRating
limit 1 ; limit the results to only one
This query probably takes a while, so it makes sense to not do this on every page request. You store the result in photo_of_day
once by a script that runs once at midnight.
Something like this. I'm not sure about 'new photo of the day must not be already in photo_of_day table', but try this one -
SET @exact_datetime = NOW();
SELECT p.*, SUM(r.RatingValue * r.RatingStrength) AS real_rating FROM photos p
JOIN ratings r
ON p.PhotoID = r.PhotoID
WHERE
p.DateOf <= @exact_datetime - INTERVAL 1 DAY
GROUP BY
p.PhotoID
HAVING
count(*) >= 10
ORDER BY
real_rating DESC
LIMIT 1
精彩评论