问个多表连接查询的问题

xueyhfeng 2006-07-14 10:04:21
有三个表,结构分别如下
A:
CommentID int ,
TopicID int ,
TopicType tinyint ,
Content ntext

B:
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])

...全文
169 6 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
xueyhfeng 2006-07-17
  • 打赏
  • 举报
回复
已经搞定,使用了游标和表变量来读取临时数据,最后一次性返回结果集的方法,
十一月猪 2006-07-14
  • 打赏
  • 举报
回复
不好意思 多了union
十一月猪 2006-07-14
  • 打赏
  • 举报
回复
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
xueyhfeng 2006-07-14
  • 打赏
  • 举报
回复
谢楼上的解决方案,怎样解决标题重复的问题呢,就是想只用TopicID和TopicType作为distinct的标准,但SQL SERVER好象不支持distinct on这样的语法,
wgsasd311 2006-07-14
  • 打赏
  • 举报
回复
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
xueyhfeng 2006-07-14
  • 打赏
  • 举报
回复
我一直怀疑这样的数据库设计是有问题的,看起来省了一个表,但是这个表是完全没有必要省的,不过已经是这样了,怎么查才能得到上面的效果呢?

34,837

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧