使用匿名外键连接表

Tom*_*len 0 sql database-design guid foreign-keys foreign-key-relationship

有关

与我的其他问题相关:

评论系统设计

数据设计

假设我有一个标签表:

tblTags
-------------
TagID (int)
Name (string)
Run Code Online (Sandbox Code Playgroud)

还有两个内容表:

tblBlogs
-------------
Anchor (GUID, Primary Key)
BlogTitle (string)
+ More custom fields

tblTutorials
-------------
Anchor (GUID, Primary Key)
TutorialTitle (string)
+ More custom fields
Run Code Online (Sandbox Code Playgroud)

还会有更多带有锚点的表格,它不仅仅是2.

然后将标签与上述实体相关联:

tblTagAnchors
-------------
TagID (int, Foreign Key)
Anchor (GUID, Foreign Key)
Run Code Online (Sandbox Code Playgroud)

我的问题是,一旦我建立了博客和教程与特定标签的关联,有没有办法编写一个查询来返回带有特定标签的博客或教程?无需对博客和教程进行单独查询?

主要用途是搜索,类似于(伪):

select from tblBlogs and tblTutorials where the GUID exists in tblTagAnchors where tagID = 5

for each record returned
    if record from Blog
        response.write("<a href=blogView.aspx?ID=" + recID)
    else if record from Tutorial
        response.write("<a href=tutorialView.aspx?ID=" + recID)
next
Run Code Online (Sandbox Code Playgroud)

我正在使用SQL Server 2008 Express和ASP.net 4(c#),如果它与Linq to SQL有很大不同,但我需要的是基于设计的答案,除非是为了演示,否则不需要任何代码.

是多方查询的唯一方法吗?

Dam*_*vic 5

这将是"通常的"方法.

在此输入图像描述

select
      p.PublicationID 
    , p.PublicationType 
    , p.PublicationTitle
    , t.TagID
    -- other blog/tutorial specific fields here
from Publication    as p
left join Blog      as b on (b.PublicationID = p.PublicationID and p.PublicationType = 'B')
left join Tutorial  as t on (t.PublicationID = p.PublicationID and p.PublicationType = 'T')
join PublicationTag as x on x.PublicationID = p.PublicationID
join Tag            as t on t.TagID = x.TagID ;
Run Code Online (Sandbox Code Playgroud)

您可以将其打包到视图中,以帮助隔离应用程序代码中的任何未来架构更改.