0

I'm trying to create a query to update the rank field of all the records in the table, based on values from the same table.

I managed to get a working SELECT query that calculates the rank, but I'm having a hard time converting it to an UPDATE. This is the query:

SELECT
  ((views_count + comments_count) * (172800 / elapsed)) AS rank
FROM (
  SELECT
    p.views_count,
    (UNIX_TIMESTAMP(NOW()) - UNIX_TIMESTAMP(p.createdAt)) AS elapsed,
    (SELECT COUNT(*) FROM `comments` AS c WHERE c.photo_id = p.id) AS comments_count
  FROM `photos` AS p
) AS m

How can I implant it in an UPDATE query, to update each record's rank value?

Thanks! :)

EDIT:

My DB structure:

[Photo]
id
user_id
views_count
rank
createdAt

[Comment]
id
photo_id
content
tamir
  • 3,207
  • 2
  • 33
  • 51

2 Answers2

0

Just a guess, but something like this should work:

UPDATE `photos`
FROM (
   SELECT id
        , (views_count + comments_count) * (172800 / elapsed) AS rank
   FROM (
      SELECT p.id
           , p.views_count
           , (  UNIX_TIMESTAMP(NOW()) 
              - UNIX_TIMESTAMP(p.createdAt)) AS elapsed
           , (SELECT COUNT(*) 
              FROM `comments` AS c 
              WHERE c.photo_id = p.id) AS comments_count
      FROM `photos` AS p
      ) AS m
   ) AS z
SET rank=z.rank
WHERE `photos`.id=z.id
BellevueBob
  • 9,498
  • 5
  • 29
  • 56
-1

You should write your new ranks to a temporary table and use that to update the original table. try

CREATE TEMPORARY TABLE tmp_tbl AS (
   SELECT ((views_count + comments_count) * (172800 / elapsed)) AS rank, m.id
      FROM (SELECT
         p.views_count,
         (UNIX_TIMESTAMP(NOW()) - UNIX_TIMESTAMP(p.createdAt)) AS elapsed,
         (SELECT COUNT(*) FROM `comments` AS c WHERE c.photo_id = p.id) AS comments_count
         FROM `photos` AS p
      ) AS m);

and then

UPDATE photos, tmp_tbl SET photos.rank = tmp_tbl.rank WHERE photos.id=tmp_tbl.id;

and finally

DROP TABLE tmp_tbl;

See this simliar stackoverflow question

Community
  • 1
  • 1
luksch
  • 11,497
  • 6
  • 38
  • 53