我偶然发现了一个数据库设计,其中一个表在一列中包含需要连接的表的名称,在另一列中包含该表的外键(整数,而不是外键名称)。
我想知道你会如何解决这个问题?
这是目前的情况:
table 上聊天:
id | someColumn | chatter_id | chatter_ref
--------------------------------------------------------
1 2 1 customers
2 3 1 colleagues
3 4 2 customers
餐 table 顾客:
id | colA
-------------
1 whatever
2 hello_world
同 table :
id | colB
-------------
1 yesyes
编辑:
我会做的是拥有多个chatting
表,每个引用表一个。
像这样:
表 chatting_customers(带有指向 customers 表的外键):
id | someColumn | chatter_id
------------------------------------
1 2 1
3 4 2
表 chatting_colleagues(带有同事表的外键):
id | someColumn | chatter_id
------------------------------------
2 3 1
而不是连接所有表并根据列 chatter_ref 决定从哪个表中选择(使用 select case when chatter_ref = 'customers' then customers.colA else colleagues.colB end from ...
) 我会union
多个查询。这是要走的路吗?有没有更好的方法来正常化这个?
最佳答案
这是经典的多态关联反模式。有许多可能的解决方案:
1 Exclusive Arcs(按照 Argeman 的建议),例如聊天 table
id | someColumn | customerId | colleagueId
------------------------------------------
1 2 1
2 3 1
3 4 2
其中 customerId 和 colleagueID 都可以为 null,并且只有一个不能为 null。可以在 customerId 和 colleagueId 上声明外键。
2 反转关系,例如从聊天表中删除 chatterId 和 chatterRef 并创建两个新表
客户聊天
chattingId | customerId
-----------------------
1 1
3 2
同事聊天
chattingId | colleagueId
------------------------
2 1
可以在 customerId 和 colleagueId 上声明外键。
3 为客户/同事(例如person)创建一个父类(super class)型表,让聊天表引用这个新表的主键。
关于mysql - 如何解决 "tablename to be joined in a table"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24904487/