[英]Is there any syntax for adding new record between two records in sql table?
Please suggest how to insert new record between two records.请建议如何在两条记录之间插入新记录。 Id 3 of record/row is missed between id 2 and 4 in sql table.
sql 表中的 id 2 和 4 之间的记录/行的 ID 3 缺失。
SQL tables are unordered sets. SQL 表是无序集。 You cannot add a record "between two records", because there is no order to the records.
您不能在“两条记录之间”添加记录,因为记录没有顺序。 Even if your queries seem to return the rows in some order, it's completely arbitrary, and unless you have an explicit
order by
clause could very well change.即使您的查询似乎以某种顺序返回行,它也是完全任意的,除非您有明确的
order by
子句,否则很可能会发生变化。
In other words - you should just insert the new row, and if you care about ordering by the id, always use order by id
in your queries.换句话说 - 您应该只插入新行,如果您关心按 id 排序,请始终在查询中使用
order by id
。
You could use a calendar table based approach here:您可以在此处使用基于日历表的方法:
INSERT INTO yourTable (id)
SELECT t1.id
FROM
(
SELECT 1 AS id UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL
SELECT 4 UNION ALL SELECT 5
) t1
LEFT JOIN yourTable t2
ON t2.id = t1.id
WHERE
t1.id IS NULL;
In practice, you might replace the inlined subquery aliased as t1
above with a bona fide sequence table covering all id
values which you would want to cover.在实践中,您可以用一个真正的序列表替换上面别名为
t1
的内联子查询,该序列表涵盖您想要涵盖的所有id
值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.