有三个表,结构分别如下
A:
  CommentID int ,
  TopicID int ,
  TopicType tinyint ,
  Content ntextB:
  TopicID int,
  Title nvarvhar(100)
C:
  TopicID int ,
  Title nvarchar(100)其中A表的TopicID字段对应B,C表的TopicID字段,A表的TopicType字段用于区分TopicID字段是属于B表还是C表,我现在要的查询效果是:
查询A表中的所有记录,与B,C表中对应的Title字段,并且A表中的TopicID,TopicType字段不发生重复。(其实也就是不产生重复的标题[Title])

解决方案 »

  1.   

    select distinct a.topicid,title=(case topictype when 'b' then b.title else c.title end)
    from ta a left join tb b on a.topicid=b.topicid
    left join tc c on a.topicid=c.topicid
      

  2.   

    谢楼上的解决方案,怎样解决标题重复的问题呢,就是想只用TopicID和TopicType作为distinct的标准,但SQL SERVER好象不支持distinct on这样的语法,
      

  3.   

    select TopicID  ,
            title
    from 
    (select * from a 
    where topictype = 'B') tab1
    inner join b on 
    tab1.title = b.title
    union
    select TopicID  ,
            title
    from 
    (select * from a 
    where topictype = 'A') tab2
    inner join C on 
    tab2.title = C.title
    union