sql关联查询问题

strife013 2012-01-26 11:28:16
关联表a,b

a 有字段code
b 关联字段code

有个需求返回a表所有数据,
并且检查对应b中的code是否有对应值,如果有则加一列selected为true,否则自定义字段selected为
...全文
106 11 打赏 收藏 转发到动态 举报
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
pengpeng409 2012-06-06
  • 打赏
  • 举报
回复

if object_id('[ta]')is not null
drop table ta
create table ta
(
acode varchar(20),
selected varchar(20)
)
insert into ta(acode,selected)
select '111',''
union all
select '222',''
union all
select '333',''

if object_id('[tb]')is not null
drop table tb
create table tb
(
bcode varchar(20)
)
insert into tb(bcode)
select '111'
union all
select '222'


select acode,case when acode=bcode then 'true'
else 'false' end as flag
from ta left join tb
on ta.acode=tb.bcode
pengpeng409 2012-06-06
  • 打赏
  • 举报
回复
if object_id('[ta]')is not null
drop table ta
create table ta
(
acode varchar(20),
selected varchar(20)
)
insert into ta(acode,selected)
select '111',''
union all
select '222',''
union all
select '333',''

if object_id('[tb]')is not null
drop table tb
create table tb
(
bcode varchar(20)
)
insert into tb(bcode)
select '111'
union all
select '222'


select acode,case when acode=bcode then 'true'
else 'false' end as flag
from ta left join tb
on ta.acode=tb.bcode
Page 2012-06-06
  • 打赏
  • 举报
回复
left join/right join/full join/inner join 都试试
小和桑 2012-01-29
  • 打赏
  • 举报
回复
这个不是没有错误么?
[Quote=引用 2 楼 zebraol 的回复:]

select a.*, case when b.code is null then 'true' else 'false' end as selected
from a left join b
on a.code=b.code;
[/Quote]
tadoll 2012-01-27
  • 打赏
  • 举报
回复
学习发帖,不会出那个sql框啊
tadoll 2012-01-27
  • 打赏
  • 举报
回复

select (' and '+case when 1=1 then 'c1 is null' else 'c1 is not null 'end) aa
tadoll 2012-01-27
  • 打赏
  • 举报
回复

select a.*, case when b.code is null then 'true' else 'false' end as selected
from a left join b
on a.code=b.code;
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 zebraol 的回复:]

select a.*, case when b.code is null then 'true' else 'false' end as selected
from a left join b
on a.code=b.code;
[/Quote]

貌似这个可以,试试,出问题再提出来
strife013 2012-01-26
  • 打赏
  • 举报
回复
left join搞不定,要求是显示a表全部数据但是不能重复显示,就是说有3条数据就显示3条数据
zebraol 2012-01-26
  • 打赏
  • 举报
回复
select a.*, case when b.code is null then 'true' else 'false' end as selected
from a left join b
on a.code=b.code;
wnf2009 2012-01-26
  • 打赏
  • 举报
回复
用left join

34,594

社区成员

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

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