mysql bitand函式 有趣的SQL 一

2021-10-17 20:33:37 字數 2937 閱讀 7779

需求:如下所示,有從1開始的2的冪的陣列

- - 1, 2, 4, 8, 16, 32, 64, 128

想求出如下結果,如,輸入17 在上面的陣列中應得出

例:輸入值 17 : 1 + 16

輸入值 31 : 1 + 2 + 4 + 16

輸入值 32 : 32

想實現如上功能,首先我們需要得出比起特定輸入值小的特定陣列

這裡我們用oracle 提供的connect by 來實現

sql> select level from dual connect by level < 17;

level

16 rows selected.

從上的sql中我們已經實現了,但是我們需要的是:有從1開始的2的冪的陣列

也是就是 power(2, level - 1)

sql> select level ,power(2, level - 1) x from dual connect by level < 17;

level x

1 12 2

3 44 8

5 16

6 32

7 64

8 128

9 256

10 512

11 1024

12 2048

13 4096

14 8192

15 16384

16 32768

16 rows selected.

但是行數16行顯然有很多沒必要的值,我們需要加大跳躍步數

sql> select 17 ,power(2, level - 1) x from dual connect by power(2, level - 1) <= 17;

17 x

17 1

17 2

17 4

17 8

17 16

現在已經求出了 如上述所示的結果 , 現在我們就剩下怎樣把1,16 得出

oracle 給我們提供了 bitand 函式,是用來比較兩個二進位制數與運算(and運算)

下面是 網上查到的 bitand 函式的用法和案例

bitand( ) 函式

返回兩個數值型數值在按位進行 and 運算後的結果。

語法bitand(nexpression1, nexpression2)

引數nexpression1, nexpression2

指定按位進行 and 運算的兩個數值。如果 nexpression1 和 nexpression2 為非整數型,那 麼它們在按位進行 and 運算之前轉換為整數。

返回值型別

數值型說明 bitand( ) 將 nexpression1 的每一位同 nexpression2 的相應位進行比較。如果 nexpression1 和 nexpression2 的位都是 1,相應的結果位就是 1;否則相應的結果位是 0。

下表列出對 nexpression1 和 nexpression2 按位進行 and 運算的結果:

nexpression1 位 nexpression2 位 結果位

bitand( ) 函式示例

x = 5 && 二進位制為 0101

y = 6 && 二進位制為 0110

bitand(x,y) && 返回值 4,二進位制為 0100

sql> select 17 ,power(2, level - 1) x ,bitand(17,power(2, level - 1) ) xy from dual connect by power(2, level - 1) < 17;

17 x xy

17 1 1

17 2 0

17 4 0

17 8 0

17 16 16

現在的情況下只要求出大於0的部分就可以了

sql> select x from (

2 select 17 ,power(2, level - 1) x ,bitand(17,power(2, level - 1) ) xy from dual connect by power(2, level - 1) <= 17

3 )where xy >0;

x整理之後如下

sql> select x

2 , power(2, level - 1) y

3 from (select 17 x from dual)

4 where bitand(x, power(2, level - 1)) > 0

5 connect by power(2, level - 1) <= x;

x y17 1

17 16

sql> select x

2 , power(2, level - 1) y

3 from (select 31 x from dual)

4 where bitand(x, power(2, level - 1)) > 0

5 connect by power(2, level - 1) <= x;

x y31 1

31 2

31 4

31 8

31 16

sql>

sql> select x

2 , power(2, level - 1) y

3 from (select 32 x from dual)

4 where bitand(x, power(2, level - 1)) > 0

5 connect by power(2, level - 1) <= x

6 ;x y

32 32

雖然這種sql 比較複雜,但是因為有網路的存在我們可以蒐集類似這樣的sql,萬一以後我們能用的上呢。

我是知數堂sql優化班老師-鄭松華

掃碼報名

2019.7.18 20:30

《如何制定sql「減脂計畫」》

end掃碼加入mysql的技術q群

有趣的 realloc 函式

在 c 語言中,我們最熟悉的函式排行榜上,malloc 和 free 想必名列前茅,而 realloc 則可能就要靠後了。不過你知道嗎,有了 realloc 函式,你甚至可以不使用 malloc 或者 free,而是由它一力承擔。該函式的原型如下 void realloc void ptr,size...

有趣的C 本地函式

目錄 究竟什麼是本地函式?使用本地函式清理注釋 借助本地函式全力以赴閱讀rainbow 測試,測試,本地的!選擇自己的冒險 許多流行的語言都支援使用本地函式,並且在c 7中,對它們的支援幾乎沒有大張旗鼓地宣布。作為乙個自認為是 c 超級使用者的人,我很少利用該功能,直到我意識到它對提高 可讀性有多大...

有趣的CSS函式 linear gradient

最近在做乙個專案,專案中用到了純css的邊界動效,以及css絢麗的顏色處理,就抽時間把這幾個函式整理了一下。css 有以下幾個函式 標註css2的是指css2支援的 其他都是css3支援的 attr 返回選擇元素的屬性值 css2 calc 允許計算 css 的屬性值,比如動態計算長度值。cubic...