日期:2014-05-16  浏览次数:20781 次

联表查询的一条sql语句,大家帮帮忙啊
table_a中的数据为:
id       userid
1         aaa
2         bbb
3         ccc

table_b中的数据为:
userid   username   youxiao
aaa         张三         0
aaa         李四         1
aaa         王五         0
bbb         张六         0
bbb         李七         0
bbb         王八         0
ccc         张九         0
ccc         李十         0
ccc         王零         1

我想得到的记录为:
1       李四
2       张六
3       王零

也就是:如果tableb中的youxiao字段为1,则优先取1的这条记录,没有,则取一条为0的记录,应该怎么写啊,多谢各位了

------解决方案--------------------

--如果不存在youxiao=1的B表数据,则随便获取一条
select
ID,
(select top 1 username from table_b where userid=A.userid order by youxiao desc) as username
from table_a as A


/*
--结果

1 李四
2 李七
3 王零

*/


--如果不存在youxiao=1的B表数据,则取第一条
select
ID,
isnull((select top 1 username from table_b where userid=A.userid and youxiao=1),(select top 1 username from table_b where userid=A.userid)) as username
from table_a as A


/*
--结果

1 李四
2 张六
3 王零

*/