0

我有两个 SQL Server 表作者和文章,其中作者主键 (AuthorID) 是文章表中的外键,以表示作者和文章表之间的简单一对多关系。现在问题来了,我需要根据名字、姓氏和传记列对作者表进行全文搜索。全文搜索工作很棒,排名等等。现在我需要在搜索中再添加一个条件,我需要从搜索中忽略所有非文章贡献者。为了实现这一点,我选择创建一个包含所有有文章的贡献者的视图,并针对该视图进行搜索。所以我以这种方式创建了视图:

    Create View vw_Contributors_With_Articles
AS 
Select * from Authors
Where Authors.ContributorID 
IN ( Select Distinct (Articles.ContributorId) From Articles)

它正在工作,但我真的不喜欢子查询。加入让我得到了所有多余的 authorID,尝试了不同的但没有使用 biography 列,因为它的类型是 ntext。Group by 不会为我做这件事,因为我需要所有列而不是它们的任何聚合。

你们觉得怎么样?我该如何改进呢?

4

3 回答 3

5

当每个作者有多篇文章时,EXISTS 允许潜在的重复条目:

Select * from Authors
Where EXISTS (SELECT *
    FROM Articles
    WHERE Articles.ContributorId = Authors.ContributorId)

编辑:为了澄清,您不能对 ntext 列进行 DISTINCT。所以,你不能有一个 JOIN 解决方案,除非你在 JOIN 中对文章使用派生表并避免直接使用文章。或者您将 ntext 转换为 nvarchar(max)。

EXISTS 或 IN 是您唯一的选择。

编辑2:

...除非您真的想使用 JOIN 并且您拥有 SQL Server 2005 或更高版本,否则您可以 CAST 和 DISTINCT(聚合)以避免输出中出现多行...

select DISTINCT
  Authors.ContributorID,
  Authors.AnotherColumn,
  CAST(Authors.biography AS nvarchar(max)) AS biography,
  Authors.YetAnotherColumn,
  ...
from
  Authors
inner join
  Articles on
  Articles.ContributorID = Authors.ContributorID
于 2009-09-13T12:42:21.367 回答
0

你想要一个内部连接

select
  *
from
  Authors
inner join
  Articles on
  Articles.ContributorID = Authors.ContributorID

这将只返回在表上有条目的作者Articles,与ContributorID.

于 2009-09-13T12:37:42.640 回答
0

从 Articles 表中选择不同的贡献者 ID 以获取撰写文章的各个作者,并将 Authors 表连接到该查询 - 就像这样

select distinct Articles.contributorID, Authors.*
from Articles
join Authors on Articles.contributerID = Authors.ContributerId
于 2009-09-13T13:00:45.200 回答