【问题标题】:Make sure a product has at least one category确保产品至少有一个类别
【发布时间】:2023-03-20 10:06:01
【问题描述】:

你好精彩的 Stackoverflowrian!

我有这个DB diagram,我有这个 postgresql 来创建表:

CREATE TABLE products (    
    prod_id serial PRIMARY KEY,
    name varchar(150) NOT NULL,
    description text,
    purchase_price numeric(10,2) NOT NULL,
    selling_price numeric(10,2) NOT NULL,
    weight numeric(10,2),
    min_quantity int NOT NULL
);

CREATE TABLE categories (
    cat_id serial PRIMARY KEY,
    name varchar(100),
    parent int REFERENCES categories ON DELETE CASCADE
);

CREATE TABLE product_categories (
    prod_id int NOT NULL REFERENCES products,
    cat_id int NOT NULL REFERENCES categories,
    PRIMARY KEY (prod_id, cat_id)
);

如您所见,我的类别包含多个子类别、产品和表格,以便在它们之间建立关系,因此我可以将多个类别分配给一个产品。 在写下创建表查询时,我脑海中会弹出有趣的问题。

我不确定这是否可能,但我正在尝试找到一种方法来确保每个产品都至少分配到一个类别。有什么想法吗?

【问题讨论】:

  • 应该由您的应用程序而不是从数据库处理吗?

标签: sql postgresql


【解决方案1】:

确保每个产品至少属于一个类别的一种方法是在产品表中拥有一个“主要”类别:

primary_categoryid int not null references categories(cat_id)

这确实使主要 categoryid 与其他类别“不同”,因为它不在 product_categories 表中。

如果您尝试在 product_categories 中需要一行的解决方案,那么您就有问题了。 product_categories 中的行需要引用有效的产品——但产品在具有类别之前是无效的(根据您的定义)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-13
    • 1970-01-01
    • 2022-06-10
    • 1970-01-01
    相关资源
    最近更新 更多