0

有一个包含 5 列的表:id, data, category, time, page。我想获取id>given idcategory=的行given category,将它们分组page,从每个页面中获取第一个按排序的页面time并减少page该行中的列。(time不是唯一的)

我设法创建了这个查询并且它有效,但我想知道是否有更好的解决方案。我在选择适当的问题标题时也遇到了问题,所以如果您认为这不完全是应该的,请随时纠正我。

UPDATE `content` AS TABLE1
    INNER JOIN (SELECT MIN(TABLE2.`id`) AS ID, TABLE2.`page` FROM `content` AS TABLE2
        INNER JOIN (
            SELECT DISTINCT `page`, MIN(`time`) AS MINTIME
            FROM `content` 
            WHERE (`page` > (SELECT `page` FROM `content` WHERE `id` = ?) AND `category` = ?)
            GROUP BY `page`) AS TABLE3
        ON TABLE2.`page` = TABLE3.`page` AND TABLE2.`time` = TABLE3.MINTIME
        GROUP BY TABLE2.`page`) AS TABLE4
    ON TABLE1.`id` = TABLE4.ID
SET TABLE1.`page` = TABLE1.`page` - 1
4

1 回答 1

0

这个怎么样。您不需要 @ 变量,但我不想在 SQL 中使用问号:

SET @id:= <given id>;

UPDATE
  content c1 LEFT JOIN content c2 ON c1.page = c2.page AND 
                                     c1.category = c2.category AND 
                                     c2.time < c1.time AND c2.id > @id
SET c1.page=c1.page-1
WHERE 
  c1.id > @id AND
  c2.id IS NULL AND
  c1.category = '<given category>';
于 2013-10-22T19:32:16.360 回答