table_a中的数据为:
id   userid
1    aaa
2    bbb
3    ccctable_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的记录,应该怎么写啊,多谢各位了

解决方案 »

  1.   


    --如果不存在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
      

  2.   


    --如果不存在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        王零*/