代码之家  ›  专栏  ›  技术社区  ›  Ahmed

只选择有文章的作者?

  •  0
  • Ahmed  · 技术社区  · 16 年前


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

    它正在工作,但我真的不喜欢子查询。这个连接让我获得了所有冗余的authorID,尝试了不同的方式,但无法与传记列一起使用,因为它的类型是ntext。Group by不会为我做这件事,因为我需要所有的列,而不是它们的任何集合。

    伙计们,你们觉得呢?我该如何改进这一点?

    3 回复  |  直到 16 年前
        1
  •  5
  •   gbn    16 年前

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

    编辑: 为了澄清,您不能对ntext列进行区分。因此,您不能有JOIN解决方案,除非您在JOIN中对项目使用派生表并避免直接使用项目。或者将ntext转换为nvarchar(max)。

    EXISTS或IN是您唯一的选择。

    编辑2:

    除非你 要使用JOIN,并且您有SQLServer2005或更高版本,您可以使用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
    
        2
  •  0
  •   Noon Silk    16 年前

    你想要一个内心的连接

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

    这将只返回在 Articles 表,匹配 ContributorID .

        3
  •  0
  •   blowdart    16 年前

    从Articles表中选择不同的贡献者ID,以获取撰写文章的各个作者,并将authors表连接到该查询中,如下所示

    select distinct Articles.contributorID, Authors.*
    from Articles
    join Authors on Articles.contributerID = Authors.ContributerId