我正在使用的旧数据库设计使用位掩码。我有一个表,该表可容纳电子邮件地址和一个基于另一个表的位掩码,并且已受命编写“分解”这些位掩码的SQL查询。通常,以不同的方式查看此数据,我们使用按位&来确定位掩码是否有效,但这次不是这种情况...
在我的数据的简化版本中,我有2个类似的字段。
|---------------------|------------------|
| Email | bitMask |
|---------------------|------------------|
| test@test.com | 3 |
|---------------------|------------------|
| test2@test.com | 9 |
|---------------------|------------------|
我最终要寻找的输出将显示到达位掩码所需的“ 2的幂”或“位”,因此我可以交叉引用另一个表中的掩码值。所以我的示例输出是这样的:
|---------------------|------------------|
| Email | value |
|---------------------|------------------|
| test@test.com | 2 |
|---------------------|------------------|
| test@test.com | 1 |
|---------------------|------------------|
| test2@test.com | 8 |
|---------------------|------------------|
| test2@test.com | 1 |
|---------------------|------------------|
这是我用来处理位掩码的相反方法。如果有人知道如何编写此查询,请多多指教。
使用&
(按位与运算符)with 0xFFFFFFFE
来获得2的幂,并且with 1
来获得第一个二进制数字(0
或1
):
select [Email], [bitMask] & 0xFFFFFFFE [value]
from tablename
union all
select [Email], [bitMask] & 1
from tablename
order by [Email], [value] desc
参见演示。
结果:
> Email | value
> :------------- | ----:
> test@test.com | 2
> test@test.com | 1
> test2@test.com | 8
> test2@test.com | 1