反转sql表中的id
我有一个带有主 ID 的表
1 西默
2 帕万
3深
4只羊
5人
我想颠倒这个顺序
5 西默尔
4 帕万
3深
2只羊
1 man
我如何通过编程或 SQL 来做到这一点? 我不想在 sql 中使用 order by
i have a table with primary id
1 simer
2 pawan
3 deep
4 sheep
5 man
i want reverse this order
5 simer
4 pawan
3 deep
2 sheep
1 man
how can i do this with programming or sql?
i dont want to use order by in sql
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
要么:
1)选择按 id 降序排列的所有行,然后将它们按升序插入到新表中,该表的 AUTO_INCRMENT 将以相反的顺序分配标识符。现在,您可以将这些行及其新标识符复制回原始表。
2) 选择按 id 降序排列的所有行到程序中,删除它们,然后使用新的 ID 重新插入它们:
Either:
1) Select all the rows ordered by id in descending order, then insert them into a new table in ascending order, and that table's AUTO_INCREMENT will assign the identifiers in reverse order. Now you can copy those rows back to the original table with their new identifiers.
2) Select all the rows ordered by id in descending order into a program, delete them, and reinsert them with the new IDs:
但这正是 SQL 提供 ORDER BY 子句的原因。
您只是想反转当前数据的顺序还是希望系统为新记录分配递减的序列号?
前者将是后者的先决条件,所以......
请注意,虽然您可以控制每个新自动增量值与前一个值的差异量(通过指定 auto_increment_increment),但简单地将其设置为 -1 并不能解决问题问题是,这个增量所应用的基值是 SELECT MAX(id) FROM yourtable - 所以即使 mysql 允许你指定 auto_increment_increment 为 -1,你最终也会得到重复的行,因此你需要复制架构中所有对 auto_increment 类型的引用都使用直整数,并使用序列生成器。然后您需要重写所有代码以使用序列生成器而不是 INSERT_ID() / mysql_insert_id()。
使用 ORDER BY 不是更简单吗?
But this is exactly the reason that SQL provides the ORDER BY clause.
Do you simply want to reverse the order of the current data or do you want your system ro assign decreasing sequence numbers to new records?
The former would be a pre-requisite for the latter so....
Note that while you can control the amount by which each new autoincrement value differs from the previous (by specifying the auto_increment_increment), simply setting this to -1 would not solve the problem as the base value this delta is applied to is SELECT MAX(id) FROM yourtable - so even if mysql allowed you to specify an auto_increment_increment of -1, you'd end up with duplicate rows, therefore you'd need to repliace all references to auto_increment types in your schema with straight integers and use a sequence generator instead. Then you'd need to rewrite all your code to use the sequence generator instead of INSERT_ID() / mysql_insert_id().
Wouldn't it be simpler to just use ORDER BY?