douhao2026 2012-04-10 00:29
浏览 139
已采纳

在insert ... select语句mysql中插入增量值

I am trying to select a number of rows in a table, reverse the values in one column and reinsert them into the table. Here is an example of what I am doing, say I have the following data:

+-------+--------+-------+
| ORDER |   X    |   Y   |
+-------+--------+-------+
|  0    |   12   |   5   |
|  1    |   16   |   3   |
|  2    |   19   |   2   |
+-------+--------+-------+

I want to select it and reinsert it into the same table with the ORDER reversed as so:

+--------+--------+-------+
| PORDER |   X    |   Y   |
+--------+--------+-------+
|  2     |   12   |   5   |
|  1     |   16   |   3   |
|  0     |   19   |   2   |
+--------+--------+-------+

I am able to duplicate the rows and reinsert them, no problem using an insert ... select like this:

INSERT INTO myTable (porder, x, y) SELECT porder, x, y FROM myTable 

but I have had no success reversing the order. I have tried

INSERT INTO myTable (porder, x, y) SELECT (SELECT porder FROM myTable ORDER BY porder DESC), x, y FROM myTable but that throws an error

It would be fine to simply ignore the porder column and insert new values from 0 to the highest number in the sequence (2 in my above example) but I don't know how to add sequential numbers in a multiple-row insert statement in mysql.

I know how to do this with php but I was thinking there must be a more elegant solution in just SQL

  • 写回答

2条回答 默认 最新

  • dpbv85276 2012-04-10 06:03
    关注

    try this

        INSERT INTO myTable(`porder`, x, y) SELECT (SELECT MAX(`porder`) FROM myTable) - `porder`, x, y FROM myTable
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?