在我的网络应用程序中,我有一个company
,可以是buyer
或supplier
或两者兼而有之。
所以我的数据库表就像这样
Company( id_company, ..., is_buyer, is_supplier, ... )
或者:
Company( id_company, ... )
Type_company( id_type_company, type )
Extra_table(id_company, id_type_company )
或者:
Company( id_company, ... )
Type_company( id_company, id_type_company, type )
如果可能,我希望每个案例都有一个解释(优点和缺点)。
答案 0 :(得分:2)
你可以考虑使用像这样的普通超类
CREATE TABLE companies
(
id int not null primary key,
name varchar(128)
-- other columns
);
CREATE TABLE buyers
(
company_id int not null primary key,
foreign key (company_id) references companies (id)
);
CREATE TABLE suppliers
(
company_id int not null primary key,
foreign key (company_id) references companies (id)
);
以下是一些示例查询:
-- Select all buyers
SELECT c.id, c.name
FROM companies c JOIN buyers b
ON c.id = b.company_id;
-- Select all suppliers
SELECT c.id, c.name
FROM companies c JOIN suppliers s
ON c.id = s.company_id;
-- Select companies that are both buers and suppliers
SELECT c.id, c.name
FROM companies c JOIN buyers b
ON c.id = b.company_id JOIN suppliers s
ON c.id = s.company_id;
-- Select companies that are buers BUT NOT suppliers
SELECT c.id, c.name
FROM companies c JOIN buyers b
ON c.id = b.company_id LEFT JOIN suppliers s
ON c.id = s.company_id
WHERE s.company_id IS NULL;
这是 SQLFiddle 演示
推荐阅读: