【问题标题】:How to iterate in MySQL?如何在 MySQL 中进行迭代?
【发布时间】:2015-02-22 01:23:33
【问题描述】:

假设我这样做:

select idx from table where number = 1;

并且这个选择返回10行(例如),我想将这10行的idx列从0更新为9。我该怎么做?

更新: 这是一个查询

/ orderID / lineID /   q  / idx  /

/   1    /    1    /   1  /  0   /

/   1    /    2    /   1  /  1   /

/   1    /    3    /   1  /  2   /

/   2    /    4    /   1  / null /

/   2    /    5    /   1  / null /

/   2    /    6    /   1  / null /

/   3    /    7    /   1  / null /

/   3    /    8    /   1  / null /

我想替换 idx 的空值如下:

/ orderID / lineID /   q  / idx  /

/   1    /    1    /   1  /  0   /

/   1    /    2    /   1  /  1   /

/   1    /    3    /   1  /  2   /

/   2    /    4    /   1  /  0   /

/   2    /    5    /   1  /  1   /

/   2    /    6    /   1  /  2   /

/   3    /    7    /   1  /  0   /

/   3    /    8    /   1  /  1   /

【问题讨论】:

  • 迭代什么?问题正文暗示您只需要一个简单的UPDATE DML 语句。
  • 也许这个对你有帮助stackoverflow.com/questions/6617056/…
  • 最好的方法是使用Windowing Function。在 Sql Server 中,它是一个 Row_Number() OVER (PARTITION BY ...) 投影。不幸的是,MySql 不支持窗口函数,尽管它们自 2003 年以来一直是 ansi sql 标准的一部分。
  • 您是要在选择时计算idx,还是要实际更新表格?

标签: mysql


【解决方案1】:

对于更新,您可以使用带有语法的更新查询

> UPDATE [LOW_PRIORITY] [IGNORE] table_reference
>     SET col_name1={expr1|DEFAULT} [, col_name2={expr2|DEFAULT}] ...
>     [WHERE where_condition]
>     [ORDER BY ...]
>     [LIMIT row_count]

Refrence

你的情况

update table SET idx=9 where number = 1;

【讨论】:

    【解决方案2】:
    update table set idx = rownum where number = 1;
    

    【讨论】:

      【解决方案3】:

      如果不使用 MySql 不支持的窗口函数,我不确定如何做到这一点 :( 我所能做的就是向您展示如何在 Sql Server 中做到这一点。

      首先,基本的选择查询来演示你想要的结果:

      SELECT orderID, lineID, q, Row_Number() OVER (PARTITION BY orderID ORDER BY orderID, lineID) -1 AS idx
      FROM `table`
      ORDER BY orderID
      

      现在把它变成这样的更新查询:

      UPDATE t1 set t1.idx = t2.idx
      FROM  
      (
          SELECT orderID, lineID, q, Row_Number() OVER (PARTITION BY orderID ORDER BY orderID, lineID) -1 AS idx
          FROM `table`
          ORDER BY orderID
      ) t2
      INNER JOIN `table` t1 ON 
      WHERE t1.orderID = t2.orderID AND t1.lineID = t2.LineID AND t1.q = t2.q
      

      诀窍是您只能将窗口函数放在 SELECT 或 ORDER BY 子句中,因此您必须编写投影,然后通过主键将其连接回原始表以进行更新。

      同样,MySql 不支持窗口函数,尽管它们自 2003 年以来就已成为 SQL 标准的一部分。不过,我听说您有时可以work around this via group_concat()

      【讨论】:

        猜你喜欢
        • 2011-02-09
        • 2016-08-12
        • 1970-01-01
        • 2015-04-21
        • 1970-01-01
        • 1970-01-01
        • 2015-03-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多