SQL条件关系

时间:2011-08-04 12:46:50

标签: sql database database-design foreign-keys relational-database

我想出了两种相同想法的方法,并希望通过使用一种方法来避免任何明显的陷阱。我有一个表(tbl_post),其中一行可以与其他表(tbl_category,tbl_site,tbl_team)有很多关系。我有一个关系表来加入这些,但不知道哪个结构,条件或直接?希望以下内容能够解释......

tbl_post (simple post, can be associated with many categories, teams and sites)
* id
* title
* content

tbl_category
* id
* title
* other category only columns

tbl_team
* id
* title
* other team only columns

tbl_site
* id
* title
* other site only columns

----------------------------------------------------------
tbl_post_relationship
* id (pk)
* post_id (fk tbl_post)
* related_id (fk, dependant on related_type to either tbl_category, tbl_site or tbl_team)
* related_type (category, site or team)

____________________________________
|id|post_id|related_id|related_type|
|--|-------|----------|------------|
| 1|      1|         6|    category|
| 2|      1|         4|        site|
| 3|      1|         9|    category|
| 4|      1|         3|        team|
------------------------------------

SELECT  c.*
FROM    tbl_category c
        JOIN tbl_relationship r ON
            r.post_id = 1
            AND r.related_type = 'category'
            AND c.id = r.related_id

------------- OR ---------------

tbl_post_relationship
* id (pk)
* post_id (fk tbl_post)
* category_id (fk tbl_category)
* site_id (fk tbl_site)
* team_id (fk tbl_team)

________________________________________
|id|post_id|category_id|site_id|team_id|
|--|-------|-----------|-------|-------|
| 1|      1|          6|   NULL|   NULL|
| 2|      1|       NULL|      4|   NULL|
| 3|      1|          9|   NULL|   NULL|
| 4|      1|       NULL|   NULL|      3|
----------------------------------------

SELECT  c.*
FROM    tbl_category c
        JOIN tbl_relationship r ON
            r.post_id = 1
            AND r.category_id = c.id

因此,使用一种方法,我最终会得到很多具有NULL的列(可能有更多的表)。或者我最终得到一个简单的表来维护它,但每个连接都基于“类型”。我也知道我可以在每个关系中都有一张桌子,但是再次感觉就像有太多桌子了。任何想法/想法?

1 个答案:

答案 0 :(得分:5)

你最擅长每个关系一张桌子。你不应该担心表的数量。单个关系表的缺点有几个,风险很大:

1)如果相关表格因行而异,则无法强制执行外键,因此您的数据完整性存在风险......迟早您将拥有孤立数据。

2)查询更复杂,因为您必须使用related_type来过滤掉许多地方的关系。

3)由于2)的原因相同,查询维护成本更高,并且因为你必须在很多地方显式使用related_type常量......当你需要更改它们或添加一些时,它将是地狱。

我建议你使用正统设计...只需要3个不同的关系表:post_category,post_team,post_site。

相关问题