mapid       firstID    secondID    thirdID     forthID     n           
----------- ----------- ----------- ----------- ----------- ----------- 
1           1           2           3           4           2
2           2           3           4           5           1
3           3           4           5           2           3
4           4           3           2           1           4
有如上一个表,firstID    secondID    thirdID     forthID 存的都是userid,现在根据传入的userid查询mapid,n=1就查firstID=userid的行,n=2就查secondID=userid的行
希望是存储过程……
新手求指教

解决方案 »

  1.   

    select mapid
    from tb
    where (n=1 and firstid = ?)
       or (n=2 and secondid = ?) 
       or (n=3 and thirdid = ?)
       or (n=4 and forthid = ?)
      

  2.   

    select *
    from tab
    where n=1 and firstID = @userid  -- @userid是参数
    union all
    select *
    from tab
    where n=2 and secondID = @userid  -- @userid是参数
    union all
    select *
    from tab
    where n=3 and thirdID = @userid  -- @userid是参数
    union all
    select *
    from tab
    where n=4 and forthID = @userid  -- @userid是参数
      

  3.   

    可以用or,用union all纯属为了提高性能
      

  4.   


    现在根据传入的userid查询mapid,n=1就查firstID=userid的行,n=2就查secondID=userid的行
    --你这句话,根据userid怎么知道n等于几呢?还是所有像小三说的那意思?
      

  5.   

    select mapid from tb
    where (case n when 1 then firstID when 2 then secondId 
                                when 3 then thirdID else forthID end)=@userid