开发者

How to avoid primary key clashes when merging two identical tables with a view

开发者 https://www.devze.com 2023-03-29 12:22 出处:网络
I have a central database and a unique database for a project I am working on.The central database allows me to provide users with default options and data.

I have a central database and a unique database for a project I am working on. The central database allows me to provide users with default options and data.

The unique database matches the central database structure to allow users own customized data. I have views that union each identical table pair.

The "primary key" field in each view is 开发者_如何学Cset as a primary key in the dbml I am using (Linq-to-sql). I then add associations to other tables in the dbml.

This means that I cannot set both tables to auto-increment with a base of 0, because the primary keys are used as "foreign keys" in unique db tables (I know they're not strictly foreign keys in this instance).

Therefore in the view, I need all records from each table pair to have a unique primary key.

I have thought about setting the unique database pk base number at 1000000 or something, but this eventually may backfire on me when the global database (0 base) caught up.

I also though about prefixing each with a number in the view, e.g.

Global: 11, 12, 13, 14, 15, 16, 17, 18, 19, 110 ,111 Unique: 21, 22, 23, 24, 25, 26, 27, 28, 29, 210, 211

I am worried how this may affect performance when querying, this has to be as efficient as possible.

Not sure of the best method?


One issue with your solution is that it is brittle and would fail if you ever needed more than two sources to be merged. This may or may not be a realistic risk depending on your business scenario.

People sometimes get around this issue by using a GUID for a candidate key. In this way, your source DBs have the IDENTITY columns as PK and also a GUID which is unique but not primary in the source databases. However, in the merged view the PK is the GUID and the originial source keys (IDENTITY) are brought along for the ride but don't actually get used in PK/FK relationships.

In this type of model, the merged view typically also includes some kind of source code column which tells you where the row came from. If you do this, then source code + identity key is also a candidate key in the merged view.


Just actually had another idea:

I could set the unique to base 1 increment 2 and the global base 2 increment 2. This way, there is no crazy hack and the pk's will never clash

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号