表:
tb
有如下字段
id,Code,Sequence
1,1111,1
2,2222,2
3,3333,3
4,4444,1
5,5555,2
6,6666,4
7,7777,5
下有如下Sql语句 查询出 Sequence 为 1,2的记录
select * from tb 
where Sequence&(1|2)=Sequence
为什么也会将Sequence为3的也查出来了?
对位运算不是很懂,希望 能给解释一下???

解决方案 »

  1.   

    select * from tb 
    where Sequence&(1|2)=Sequence 
      

  2.   

    1|2 
    0001 
    0010 
    ---- 
    0011 
    3&3 
    0011 
    ---- 
    0011 
    3
      

  3.   


    ---先看括号里面的,按位或,只要哪一位中有1,就为1
    select (1|2);  01 
      10
    -----按位或运算
      11---经计算,括号里面的为3 (二进制11)
    那么:下面这个语句
    select * from tb 
    where Sequence&(1|2)=Sequence也可以写成
    select * from tb 
    where Sequence&(3)=Sequence---再看:原表记录:
    表: 
    tb 
    有如下字段 
    id,Code,Sequence   对就二进制   分别与3(011)按位与的结果
    1,1111,      1      001           001
    2,2222,      2      010           010
    3,3333,      3      011           011
    4,4444,      1      001           001
    5,5555,      2      010           010
    6,6666,      4      100           000  --不符合要求
    7,7777,      5      101           001  --不符合要求
    所以所得的查询结果应该是id为1,2,3,4的四条记录!
      

  4.   

    ---先看括号里面的,按位或,只要哪一位中有1,就为1
    select (1|2);  01 
      10
    -----按位或运算
      11---经计算,括号里面的为3 (二进制11)
    那么:下面这个语句
    select * from tb 
    where Sequence&(1|2)=Sequence也可以写成
    select * from tb 
    where Sequence&(3)=Sequence---再看:原表记录:
    表: 
    tb 
    有如下字段 
    id,Code,Sequence   对就二进制   分别与3(011)按位与的结果
    1,1111,      1      001           001
    2,2222,      2      010           010
    3,3333,      3      011           011
    4,4444,      1      001           001
    5,5555,      2      010           010
    6,6666,      4      100           000  --不符合要求
    7,7777,      5      101           001  --不符合要求
    所以所得的查询结果应该是id为1,2,3,4,5的5条记录!
    create table tb(id int, Code int, Sequence int);
    insert into tb
    select
    1,1111,1 union all select
    2,2222,2 union all select
    3,3333,3 union all select
    4,4444,1 union all select 
    5,5555,2 union all select 
    6,6666,4 union all select
    7,7777,5; select * from tb 
    where Sequence&(1|2)=Sequence
    -------------------------------------
    1 1111 1
    2 2222 2
    3 3333 3
    4 4444 1
    5 5555 2