2

I'm designing a database (for use in mysql) that permits new user-defined attributes to an entity called nodes.

To accomplish this I have created 2 other tables. One customvars table that holds all custom attributes and a *nodes_customvars* that define the relationship between nodes and customvars creating a 1..n and n..1 relationship.

Here is he link to the drawed model: Sketched database model

So far so good... But I'm not able to properly handle INSERTs and UPDATEs using separate IDs for each table.

For example, if I have a custom attribute called color in the *nodes_customvars* table inserted for a specific node, if I try to "INSERT ... ON DUPLICATE KEY UPDATE" either it will always insert or always update.

I've thinked on remove the "ID" field from the *nodes_customvars* tables and make it a composite key using nodes id and customvars id, but I'm not sure if this is the best solution...

I've read this article, and the comments, as well: http://weblogs.sqlteam.com/jeffs/archive/2007/08/23/composite_primary_keys.aspx

What is the best solution to this?

EDIT:

Complementing: I don't know the *nodes_customvars* id, only nodes id and customvars id. Analysing the *nodes_customvars* table:

1- If I make nodes id and/or customvars id UNIQUE in this table, using "INSERT ... ON DUPLICATE KEY UPDATE" will always UPDATE. Since that multiple nodes can share the same customvar, this is wrong;

2- If I don't make any UNIQUE key, "INSERT ... ON DUPLICATE KEY UPDATE" will always INSERT, since that no UNIQUE key is already found in the statement...

4

2 回答 2

0

您当前的实体设计打破了 1NF。这意味着您的架构可能会错误地存储重复数据。

nodes_customvarsnodes描述和之间的多对多关系customvars。这种类型的表有时被称为辅助表,因为它的内容纯粹是从基表(在本例中为节点和自定义变量)派生的。

描述多对多关系的辅助表的 PK 应该是复合键,以防止重复。基本上是1NF。

表上的任何 PK 本质上都是唯一的。无论它是单个键还是复合键。因此,在某些方面,您的问题没有意义,因为您正在谈论idnodesand开启/关闭 UNIQUE 约束customvarsid如果您实际上是PK,您将无法做到这一点。

那么你到底想在这里实现什么???

于 2013-06-24T02:19:58.687 回答
0

您有两种选择来解决“INSERT...ON DUPLICATE KEY”的特定问题,或者始终按照您的描述插入或更新。

  1. 使用 nodeId 和 customvarId 将主键更改为复合键(如 SyntaxGoonoo 所建议的那样,并且在您的问题中作为可能的选项)。

  2. 使用 nodeId 和 customvarId 添加复合唯一索引。

    CREATE UNIQUE INDEX IX_NODES_CUSTOMVARS ON NODES_CUSTOMVARS(nodeId, customvarId);
    

这两个选项都允许“INSERT...ON DUPLICATE KEY”功能按您的需要工作(如果 nodeId 和 customvarId 的唯一组合不存在则插入;如果存在则更新)。

至于是复合主键还是单独的主键列加上唯一索引的问题,在设计中需要考虑很多。有 1NF 考虑因素和您所在的数据库平台的物理特性以及您碰巧使用的 ORM 的偏好(如果有的话)。鉴于 InnoDB 二级索引是如何工作的(参见最后一段:http ://dev.mysql.com/doc/refman/5.0/en/innodb-index-types.html ),我建议您保持当前的设计拥有它并添加额外的唯一索引。

高温下,

-蘸

于 2013-06-24T13:09:57.277 回答