使用同一个表中的子选择更新查询

时间:2013-04-21 17:31:44

标签: mysql sql-update sql-subselect

我正在尝试创建一个查询,根据同一个表中的值更新表中所有记录的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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:-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;

See this simliar stackoverflow question