我正在实现一个每个子类的表 我在 previous question 中讨论过的设计.它是一个产品数据库,其中产品可以根据其类型具有非常不同的属性,但每种类型的属性都是固定的,并且类型根本无法管理。我有一个包含公共(public)属性的主表:
product_type
============
product_type_id INT
product_type_name VARCHAR
E.g.:
1 'Magazine'
2 'Web site'
product
=======
product_id INT
product_name VARCHAR
product_type_id INT -> Foreign key to product_type.product_type_id
valid_since DATETIME
valid_to DATETIME
E.g.
1 'Foo Magazine' 1 '1998-12-01' NULL
2 'Bar Weekly Review' 1 '2005-01-01' NULL
3 'E-commerce App' 2 '2009-10-15' NULL
4 'CMS' 2 '2010-02-01' NULL
...以及每种产品类型的子表:
item_magazine
=============
item_magazine_id INT
title VARCHAR
product_id INT -> Foreign key to product.product_id
issue_number INT
pages INT
copies INT
close_date DATETIME
release_date DATETIME
E.g.
1 'Foo Magazine Regular Issue' 1 89 52 150000 '2010-06-25' '2010-06-31'
2 'Foo Magazine Summer Special' 1 90 60 175000 '2010-07-25' '2010-07-31'
3 'Bar Weekly Review Regular Issue' 2 12 16 20000 '2010-06-01' '2010-06-02'
item_web_site
=============
item_web_site_id INT
name VARCHAR
product_id INT -> Foreign key to product.product_id
bandwidth INT
hits INT
date_from DATETIME
date_to DATETIME
E.g.
1 'The Carpet Store' 3 10 90000 '2010-06-01' NULL
2 'Penauts R Us' 3 20 180000 '2010-08-01' NULL
3 'Springfield Cattle Fair' 4 15 150000 '2010-05-01' '2010-10-31'
现在我想添加一些与特定项目相关的费用。由于子类型很少,所以这样做是可行的:
fee
===
fee_id INT
fee_description VARCHAR
item_magazine_id INT -> Foreign key to item_magazine.item_magazine_id
item_web_site_id INT -> Foreign key to item_web_site.item_web_site_id
net_price DECIMAL
E.g.:
1 'Front cover' 2 NULL 1999.99
2 'Half page' 2 NULL 500.00
3 'Square banner' NULL 3 790.50
4 'Animation' NULL 3 2000.00
我有严格的外键来处理级联版本,我想我可以添加一个约束,所以只有一个 ID 不是 NULL。
但是,我的直觉表明,去掉 item_WHATEVER_id 列并保留一个单独的表会更简洁:
fee_to_item
===========
fee_id INT -> Foreign key to fee.fee_id
product_id INT -> Foreign key to product.product_id
item_id INT -> ???
但我不知道如何在 item_id 上创建外键,因为源表因 product_id 而异。我应该坚持我最初的想法吗?
更新
我实际考虑的替代方案是:
fee
===
fee_id INT
fee_description VARCHAR
product_id INT -> Foreign key to product.product_id
item_id INT -> ???
net_price DECIMAL
我不确定为什么要提到一个单独的 fee_to_item
表(我想我在想别的东西)但它并没有真正改变问题,因为关键点是相同的:foo1_id+foo2_id+foo3_id
与 source_id+foo_id
最佳答案
我通常使用一个 FK 列和一个标志列。所以不是
fee
===
fee_id INT
fee_description VARCHAR
item_magazine_id INT -> Foreign key to item_magazine.item_magazine_id
item_web_site_id INT -> Foreign key to item_web_site.item_web_site_id
net_price DECIMAL
你会
fee
===
fee_id INT
fee_description VARCHAR
item_id INT -> Foreign key to item_magazine/website.item_magazine/website_id
product_type_id INT -> Foreign key to product_type.product_type_id
net_price DECIMAL
然后您的查询就可以概括了。而不是 2 个不同的查询,例如:
SELECT * FROM fee WHERE item_magazine_id=x
SELECT * FROM fee WHERE item_website_id=y
你做这样的事情:
SELECT * FROM fee WHERE item_id=x and product_type_id=1
SELECT * FROM fee WHERE item_id=y and product_type_id=2
关于mysql - 指向不同表的外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2721145/