表A,表B一对多关系,但要查询一对一的数据

Rex_man 2013-08-10 10:19:11
表Question(id,question)
表Answer(QuestionID,Answer,isBest)
一条Question可以有多条Answer,但是IsBest为1的数据只能一条,


现要查询一条Question对应一条Answer,(如果Answer有Isbest =1 的就选,没有就选第一条,没有数据就为空)
...全文
211 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
Rex_man 2013-08-10
  • 打赏
  • 举报
回复
引用 1 楼 lzw_0736 的回复:

select *,
isnull(
(select Answer from Answer where QuestionID=a.id and isBest=1)
,
isnull((select top 1 Answer from Answer where QuestionID=a.id order by QuestionID),'')
) Answer
from Question a
牛B啊,这个可以有,但是有一点就是我用的数据库是2000的,这个不能查数据类型为ntext,text,image的字段……去改数据库了……
Shawn 2013-08-10
  • 打赏
  • 举报
回复
select 
	A.*,
	Answer=isnull((select top 1 Answer from Answer b where B.QuestionID=a.id order by isBest DESC, QuestionID),'')
from Question A
Andy__Huang 2013-08-10
  • 打赏
  • 举报
回复
select a.*,b.* from Question a left join Answer b on a.id=b.QuestionID and b.IsBest=1
lzw_0736 2013-08-10
  • 打赏
  • 举报
回复

select *,
isnull(
(select Answer from Answer where QuestionID=a.id and isBest=1)
,
isnull((select top 1 Answer from Answer where QuestionID=a.id order by QuestionID),'')
) Answer
from Question a
唐诗三百首 2013-08-10
  • 打赏
  • 举报
回复
try this,

select a.id,a.question,isnull(b.Answer,'') 'Answer'
 from Question a
 left join
 (select * from Answer where isBest=1) b on a.id=b.QuestionID

22,209

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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