在一个数据库设计中,表中有需要连接的表名,而在另一列中,表中有外键(整数,而不是外键名),这是我在数据库设计中遇到的绊脚石。
我想知道你怎么解决这个问题?
这就是目前的情况:
桌聊:
id | someColumn | chatter_id | chatter_ref
--------------------------------------------------------
1 2 1 customers
2 3 1 colleagues
3 4 2 customers
餐桌客户:
id | colA
-------------
1 whatever
2 hello_world
同桌同事:
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
。这是该走的路吗?是否有更好的方法来规范化?
发布于 2014-07-23 17:05:39
这是典型的多态关联反模式.有一些可能的解决办法:
1个专属弧(如Argeman所建议的),例如用于聊天台
id | someColumn | customerId | colleagueId
------------------------------------------
1 2 1
2 3 1
3 4 2
其中,customerId和colleagueID都是可空的,而且确切地说,其中一个必须不是null。外键可以在customerId和colleagueId上声明。
2反转关系,例如从聊天表中删除chatterId和chatterRef,并创建两个新表
客户聊天
chattingId | customerId
-----------------------
1 1
3 2
同事聊天
chattingId | colleagueId
------------------------
2 1
外键可以在customerId和colleagueId上声明。
3为客户/同事(如个人)创建一个超级类型的表,并让聊天表引用这个新表的主键。
发布于 2014-07-23 09:28:16
我会将两个或多个可为空的行放入引用其他不同表的聊天表中。
例如,一个列chatter_colleague和一个chatter_customer。这也不是很好,但我只是不知道任何真正好的解决方案!
这需要一些努力来保持表的整洁,但据我所知,它提供了最佳的连接和索引功能。这是相当简单的,这在我看来是可取的。
发布于 2014-07-23 08:13:52
将引用表的行合并到一个“表”中,并包含源表的名称(作为一个文字值),这样您就可以区分它们,然后将主表连接到其中,同时连接id和源名称:
select
c.id,
c.someColumn,
d.data
from chatting c
left join (
select 'customers' type, id, colA data from customers
union all
select 'colleagues', id, colB from colleagues) d
on d.type = c.chatter_ref
and d.id = c.chatter_id
https://stackoverflow.com/questions/24904487
复制相似问题