自动增量字段在另一个字段更改后重置

发布于 2024-12-04 07:24:01 字数 586 浏览 2 评论 0原文

您能否提供一个非常简单的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

甜`诱少女 2024-12-11 07:24:02

这不是您应该存储在数据库中的内容。您基本上将相同的信息存储两次(在本例中它是派生的,但实际上是相同的),这可能会导致以后出现问题。您最终会在最后一行之前得到一个新的午餐行,并且订单号将被搞砸,等等。相反,只需在需要时计算数量即可。

您没有提及您正在使用哪个 RDBMS(在提问时包含该信息总是一个好主意),但类似以下内容将适用于 SQL Server 和其他支持分区函数的 RDBMS:

SELECT
    meal,
    [time],  -- I'd pick a better column name myself. Reserved words = evil
    ROW_NUMBER() OVER(PARTITION BY meal ORDER BY time) AS [order]  -- Another reserved word! Eeek!
FROM
    My_Table

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:

SELECT
    meal,
    [time],  -- I'd pick a better column name myself. Reserved words = evil
    ROW_NUMBER() OVER(PARTITION BY meal ORDER BY time) AS [order]  -- Another reserved word! Eeek!
FROM
    My_Table
为你鎻心 2024-12-11 07:24:01

不要将 Order 存储在表中,而是考虑将其添加到视图中。您可以在需要时从视图而不是表中进行选择。

视图可以使用 row_number() 来计算顺序,例如:

select  row_number() over (partition by Meal order by Time)
,       *
from    YourTable

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:

select  row_number() over (partition by Meal order by Time)
,       *
from    YourTable

Example at SE Data.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文