【问题标题】:Is there a way to implement an organization with many types without duplicating this organization?有没有办法在不复制该组织的情况下实现具有多种类型的组织?
【发布时间】:2021-03-16 23:15:02
【问题描述】:

我是 postgresql 和数据库系统的新手。

我有两张这样的表:

组织结构表

CREATE TABLE public."Organization"
(
    org_id integer NOT NULL DEFAULT nextval('"Organization_org_id_seq"'::regclass),
    org_name "char" NOT NULL,
    org_description "char" NOT NULL,
    org_email citext COLLATE pg_catalog."default" NOT NULL,
    org_phone "char" NOT NULL,
    bt_id integer,
    CONSTRAINT "Organization_pkey" PRIMARY KEY (org_id),
    CONSTRAINT bt_id1 FOREIGN KEY (bt_id)
        REFERENCES public.business_type (businesstype_id) MATCH SIMPLE
        ON UPDATE CASCADE
        ON DELETE CASCADE
        NOT VALID
)

业务类型表

CREATE TABLE public.business_type
(
    businesstype_id integer NOT NULL DEFAULT nextval('business_type_businesstype_id_seq'::regclass),
    businesstype_description "char" NOT NULL,
    CONSTRAINT business_type_pkey PRIMARY KEY (businesstype_id)
)

业务类型有 4 个值。我想实现一个系统,其中组织的类型可能介于 0 和 4 之间,而无需复制组织以具有不同的类型。对于我的架构,对于具有两种类型的组织,我需要插入组织两次,org_id 不同,bt_id 不同。

有没有一种方法可以实现一个组织具有相同 org_id 和多个 bt_id 的架构,而无需多次插入它?此外,我希望业务类型始终不同。例如,一个组织可能有业务类型 1 或 1,2,3,但不是 1,1。

【问题讨论】:

    标签: sql postgresql database-design many-to-many create-table


    【解决方案1】:

    您正在描述组织和业务类型之间的多对多关系。要存储该关系,您可以创建第三个表:

    create table organization_business_type (
        org_id integer 
            references organization(org_id)
            on delete cascade,
        businesstype_id integer 
            references business_type(businesstype_id)
            on delete cascade,
        primary key (org_id, businesstype_id)
    );
    

    这允许每个组织有 0 到 N 个业务类型,同时禁止重复(主键执行后者)。

    因此,您需要从organization 表中删除列bt_id

    旁注:在 Postgres 中,don't use upper case table or column names: public."Organization" 应该是 public.organization

    【讨论】:

      猜你喜欢
      • 2022-11-28
      • 1970-01-01
      • 2022-07-06
      • 1970-01-01
      • 1970-01-01
      • 2012-10-02
      • 1970-01-01
      • 1970-01-01
      • 2018-02-01
      相关资源
      最近更新 更多