自动增量字段在另一个字段更改后重置
您能否提供一个非常简单的 SQL 示例,说明如何创建一个自动递增的“计数”或“顺序”字段,但在不同字段的每次更改后重新启动?在下表中,每次“餐食”字段发生更改时,“订单”字段都会从“1”重新开始。谢谢。
用餐 时间 订单
午餐 10:30 1
午餐 11:00 2
午餐 11:15 3
晚餐 4:30 1
晚餐 4:45 2
晚餐 5:00 3
晚餐 5:30 4
Can you provide a very simple SQL example of how to create a "count" or "order" field that would auto-increment, but restart after every change in a different field? In the table below, the "Order" field would restart at "1" every time there was a change in the "Meal" field. Thanks.
Meal Time Order
Lunch 10:30 1
Lunch 11:00 2
Lunch 11:15 3
Dinner 4:30 1
Dinner 4:45 2
Dinner 5:00 3
Dinner 5:30 4
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这不是您应该存储在数据库中的内容。您基本上将相同的信息存储两次(在本例中它是派生的,但实际上是相同的),这可能会导致以后出现问题。您最终会在最后一行之前得到一个新的午餐行,并且订单号将被搞砸,等等。相反,只需在需要时计算数量即可。
您没有提及您正在使用哪个 RDBMS(在提问时包含该信息总是一个好主意),但类似以下内容将适用于 SQL Server 和其他支持分区函数的 RDBMS:
That's not something that you should be storing in the database. You're basically storing the same information twice (in this case it's derived, but effectively the same) which will likely result in problems down the road. You're going to end up with a new Lunch row before the last one and the order numbers will be screwed up, etc. Instead, just calculate the number when you need it.
You don't mention which RDBMS you're using (always a good idea to include that information when asking a question), but something like the following will work with SQL Server and other RDBMSs that support partition functions:
不要将
Order
存储在表中,而是考虑将其添加到视图中。您可以在需要时从视图而不是表中进行选择。视图可以使用
row_number()
来计算顺序,例如:SE Data 中的示例。
Instead of storing
Order
in the table, consider adding it to a view. You can select from the view instead of the table when you need it.The view could use
row_number()
to calculate the order, like:Example at SE Data.