使用额外的表来从其余数据中分离NULL和NOT NULL值

问题描述 投票:1回答:1

我有:

a)两种用户A和B,它们是相互排斥的,目前我更喜欢将它们分开,

b)两种服务,即A和B,它们也是相互排斥的,目前我更愿意将它们分开。

情况1

我把所有东西放在同一张桌子下面:

CREATE TABLE user_service
(
    id              bigint NOT NULL,
    user_a_id       integer,
    user_b_id       integer,
    service_a_id    smallint,
    service_b_id    smallint,
    ...
    ...
    CONSTRAINT user_service__user_check
        CHECK ((user_a_id IS NOT NULL::integer + user_b_id IS NOT NULL::integer) = 1),
    CONSTRAINT usr_service__service_check
        CHECK ((service_a_id IS NOT NULL::integer + service_b_id IS NOT NULL::integer) = 1)
    ...
);

案例2

我创建了三个表:

CREATE TABLE user
(
    id              integer NOT NULL,
    user_a_id       integer,
    user_b_id       integer,

    CONSTRAINT user_check
        CHECK ((user_a_id IS NOT NULL::integer + user_b_id IS NOT NULL::integer) = 1)
);

CREATE TABLE service
(
    id              smallint NOT NULL,
    service_a_id    smallint,
    service_b_id    smallint,

    CONSTRAINT service_check
        CHECK ((service_a_id IS NOT NULL::integer + service_b_id IS NOT NULL::integer) = 1)
);

CREATE TABLE user_service
(
    id            bigint   NOT NULL,
    user_id       integer  NOT NULL,
    service_id    smallint NOT NULL,
    ...
);

目的是保持user_service表没有NULL值。

问题:

a)除了案例2中的明显差异:i)更多空间,以及ii)需要更多编码(在功能和触发器中)还有其他技术性吗?

b)是否有一些实际可行的建议,或者它绝对没有区别?

射线

database
1个回答
0
投票

要具有最小冗余和最高正常性以及更高的可扩展性:

您有两个(可能在将来更多)类型的用户。所以你有继承自UserAUserBparentuserparentuser可以拥有UserAUserB的共同领域。

CREATE TABLE parentuser
(
    pid  integer NOT NULL, Primary Key,
    -- maybe you wnat to use UserType attribute to know the type of userA or userB
    --common fields of all users types.
);

所以,(在将继承映射到关系时)我更喜欢将pidparentuser作为UserAUserB的外键传输。 (而不是相反)

CREATE TABLE usera
(
    id              integer NOT NULL Primary Key,
    pid       integer,  -- referenced to parentid 
    -- other specific fields of UserA
);

CREATE TABLE userb
(
    id              integer NOT NULL Primary Key,
    pid       integer,  -- referenced to parentid 
    -- other specific fields of UserB
);

您可以对所有类型的服务使用相同的方法。

因此:您的用户 - 服务关系如下所示:

CREATE TABLE parentuser_parentservice
(
    id            bigint   NOT NULL Primary Key,
    parentuser_id       integer  NOT NULL,
    parentservice_id    smallint NOT NULL,
    --...
);
© www.soinside.com 2019 - 2024. All rights reserved.