0

My Table looks like something below

Id | Customer_number | Customer_Name | Customer_owner

I want to insert Customer_Number as a sequence specific to Customer_owner

that is 1,2,3,.... for Customer_owner X and 1,2,3,... Customer_owner Y.

To get the Customer_number I can use following SQL

SELECT COUNT(*) FROM Customer where Customer_owner='X'

My question is that are there any performance impact. Specially for a table with 100,000 records. Are there any better alternatives?

4

3 回答 3

1

您可以Customer_Number在需要时即时计算:

select c.*, row_number() over (partition by Customer_Owner order by id) as CustomerNumber
from Customer c

与尝试存储和维护数字相比,这是一种更安全的方法,数字可能会受到系统中各种更新的影响。例如,想象一下当现有记录更改其所有权时更改编号的乐趣。

于 2013-07-06T21:06:32.207 回答
1

在性能方面,我建议不要在 Customers 中添加另一列,原因有很多:

  1. 添加与所有者 A 的客户时,需要更新与所有者 A 相关的所有客户,删除也是如此。

  2. 客户端数量重复多次 - 占用更多空间,因此(通常)减慢执行速度。

  3. 没有实际用途通过另一列将客户数量与客户所有者联系起来,以获取描述单个客户的记录。

还有更多的解释..

正确的范式将有 2 个表格:

  1. 客户(Cust_id、Cust_name、Cust_Owner_id)

2.a. 所有者(Owner_id、Owner_name、NumberOfCustomers)

或者

2.b。所有者 (Owner_id,Owner_name) 和 NumberOfCustomers 在查询时自动计算。

编辑: 由于您想显示单个所有者的所有客户,我假设这是您的主要用途,您应该在 Cust_Owner_id 上添加一个集群索引。然后,在查询时,性能会很好,因为它具有根据您想要的数据进行聚类的好处。

在此处阅读有关集群的更多信息: 聚集索引

编辑2:

我刚刚通过最新评论意识到您的意图,但解决方案仍然存在,我会补充说,针对您的问题,我不建议您存储一个所有者的所有客户的号码,而是保留订阅日期客户表中的列,查询时根据显示的客户号确定。但是,如果您希望该数字是永久的(任何顺序 1,2,3,..n 可能会中断,因为可以删除客户),只需使用 Customer_Id,因为它已经是唯一的。

于 2013-07-06T19:41:52.080 回答
0

如果您只需要 UI 中的唯一编号,您可以在 UI 中分配编号。如果您走这条路,您需要确保始终以相同的顺序检索客户,因此添加 ORDER BY Id,或者,按照 Gordon Linoff 的建议进行操作。

于 2013-07-07T15:59:16.517 回答