0

我正在尝试创建一个查询来rank根据同一个表中的值更新表中所有记录的字段。

我设法获得了一个SELECT计算排名的有效查询,但我很难将其转换为UPDATE. 这是查询:

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

如何将其植入UPDATE查询中,以更新每条记录的rank值?

谢谢!:)

编辑:

我的数据库结构:

[Photo]
id
user_id
views_count
rank
createdAt

[Comment]
id
photo_id
content
4

2 回答 2

0

只是一个猜测,但这样的事情应该有效:

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
于 2013-04-21T17:50:11.523 回答
-1

您应该将新排名写入临时表并使用它来更新原始表。尝试

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);

接着

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

最后

DROP TABLE tmp_tbl;

看到这个类似的stackoverflow问题

于 2013-04-21T17:56:09.030 回答