Yes, you'd add all three columns. Assuming they have the same names in both tables, you'd use something like
foreign key (Name, BoughtFrom, TimeBought)
references the_other_table_name (Name, BoughtFrom, TimeBought)
If you decide to use a surrogate ID number, you'll still need a unique constraint on {Name, BoughtFrom, TimeBought}. You can do that with something along these lines.
create table your_table (
your_id_number integer primary key,
Name ... ,
BoughtFrom ... ,
TimeBought ... ,
unique (Name, BoughtFrom, TimeBought)
);
The surrogate key doesn't have to be an ID number. It doesn't have to be any kind of number. But an automatically incrementing ID number is the most common.
Surrogate means takes the place of. A surrogate key, like an ID number, takes the place of a natural key. Kind of like a surrogate mother takes the place of a natural mother.
You need FKs in category_product
table, not in categories
and products
:
CREATE TABLE IF NOT EXISTS categories (
id serial,
name text NOT NULL,
is_active boolean NOT NULL DEFAULT true,
CONSTRAINT PK_CATEGORIES_ID PRIMARY KEY (id)
);
CREATE TABLE IF NOT EXISTS products (
id serial,
name text NOT NULL,
description text NULL,
photo text NULL,
price money NOT NULL,
is_in_menu boolean NOT NULL DEFAULT true,
is_from_kitchen boolean NOT NULL DEFAULT true,
is_deleted boolean NOT NULL DEFAULT false,
CONSTRAINT PK_PRODUCTS_ID PRIMARY KEY (id)
);
CREATE TABLE IF NOT EXISTS category_product (
cat_id integer NOT NULL,
product_id integer NOT NULL,
CONSTRAINT PK_CATEGORY_PRODUCT_ID PRIMARY KEY (cat_id, product_id),
CONSTRAINT FK_CATEGORY_PRODUCT_CATEGORY FOREIGN KEY(cat_id) REFERENCES categories(id)
ON DELETE CASCADE,
CONSTRAINT FK_CATEGORY_PRODUCT_PRODUCT FOREIGN KEY(product_id) REFERENCES products(id)
);
Best Answer
This is certainly possible and even very reasonable in many situations. Think for instance to the classical Order and OrderLine tables, in which the OrderLine has as primary key the order number and the line number, with order number foreign key for the Order table.