0

我想这次我会很灵活,让用户决定希望将哪些联系信息存储在他们的数据库中。从理论上讲,它看起来像一行,例如:姓名、地址、邮政编码、类别 X、列表项 A。

定义用户可用数据类型的示例
FieldType表:

FieldTypeID, FieldTypeName, TableName
1,"Integer","tblContactInt"
2,"String50","tblContactStr50"
...

用户在FieldDefinition表中定义他的字段:

FieldDefinitionID, FieldTypeID, FieldDefinitionName
11,2,"Name"
12,2,"Address"
13,1,"Age"

最后,我们根据数据类型将实际联系人数据存储在单独的表中。主表,仅包含 ContactID

tbl联系方式

ContactID
21
22

tblContactStr50

ContactStr50ID,ContactID,FieldDefinitionID,ContactStr50Value
31,21,11,"Person A"
32,21,12,"Address of person A"
33,22,11,"Person B"

tblContactInt

ContactIntID,ContactID,FieldDefinitionID,ContactIntValue
41,22,13,27

Question: Is it possible to return the content of these tables in two rows like this:

ContactID,Name,Address,Age
21,"Person A","Address of person A",NULL
22,"Person B",NULL,27

I have looked into using the COALESCE and Temp tables, wondering if this is at all possible. Even if it is: maybe I'm only adding complexity whilst sacrificing performance for benefit in datastorage and user definition option.

What do you think?

4

1 回答 1

1

I don't think this is a good way to go because:

  • A simple insert of 1 record for a contact suddenly becomes n inserts. e.g. if you store varchar, nvarchar, int, bit, datetime, smallint and tinyint data for a contact, that's 7 inserts in datatype specific tables, +1 for the main header record
  • Likewise, a query will automatically reference 7 tables, with 6 JOINs involved just to get the full details

I personally think it's better to go for a less "generic" approach. Keep it simple.

Update: The question is, do you really need a flexible solution like this? For contact data, you always expect to be able to store at least a core set of fields (address line 1-n, first name, surname etc). If you need a way for the user to store custom/user definable data on top of that standard data set, that's a common requirement. Various options include:

  • XML column in your main Contacts table to store all the user defined data
  • 1 extra table containing key-value pair data a bit like you originally talked about but to much lesser degree! This would contain the key of the contact, the custom data item name and the value.

These have been discussed before here on SO so would be worth digging around for that question. Can't seem to find the question I'm remembering after a quick look though!

Found some that discuss the pros/cons of the key-value approach, to save repeating:
Key value pairs in relational database
Key/Value pairs in a database table

于 2010-04-13T07:00:14.473 回答