MySQL8.0.12 bit_and bit_or bit_xor
阿新 • • 發佈:2018-12-09
MySQL本身對於位運算有與或非的專屬符號 & | ^ 在MySQL中提供了bit_and、bit_or、bit_xor的分組函式。 此外MySQL還提供了bit_count函式用以統計二進位制中含有1的個數。 mysql> select bit_count(10); +---------------+ | bit_count(10) | +---------------+ | 2 | +---------------+ 1 row in set (0.00 sec) mysql> select bit_count(b'1010'); +--------------------+ | bit_count(b'1010') | +--------------------+ | 2 | +--------------------+ 1 row in set (0.00 sec) bit_or:二進位制數按位或,bit_and:二進位制數按位與,bit_count:統計二進位制數1個個數。 應用統計: mysql> create table visituser(id bigint unsigned not null auto_increment primary key,userid int,brokerid int,y int,m int(2) unsigned zerofill,d int(2) unsigned zerofill); Query OK, 0 rows affected (0.04 sec) mysql> insert into visituser(userid,brokerid,y,m,d)values(1000,1,2018,8,1),(1000,2,2018,8,15),(1000,2,2018,8,21),(1002,1,2018,9,1),(1002,1,2018,9,16),(1000,2,2018,9,20),(1000,2,2018,9,25),(1000,2,2018,9,25); Query OK, 7 rows affected (0.02 sec) Records: 7 Duplicates: 0 Warnings: 0 select y,m,count(distinct d) days from visit group by y,m; select y,m,bit_count(bit_or(1<<d)) days from visit group by y,m; select y,m,userid,brokerid,bit_count(bit_or(1<<d)) days from visituser group by y,m,userid,brokerid; mysql> select y,m,userid,brokerid,bit_count(bit_or(1<<d)) days from visituser group by y,m,userid,brokerid; +------+------+--------+----------+------+ | y | m | userid | brokerid | days | +------+------+--------+----------+------+ | 2018 | 08 | 1000 | 1 | 1 | | 2018 | 08 | 1000 | 2 | 2 | | 2018 | 09 | 1002 | 1 | 2 | | 2018 | 09 | 1000 | 2 | 2 | +------+------+--------+----------+------+ 4 rows in set (0.01 sec) count(distinct d) mysql> select y,m,userid,brokerid,count(distinct d) days from visituser group by y,m,userid,brokerid; mysql> select y,m,userid,brokerid,count(distinct d) days from visituser group by y,m,userid,brokerid; +------+------+--------+----------+------+ | y | m | userid | brokerid | days | +------+------+--------+----------+------+ | 2018 | 08 | 1000 | 1 | 1 | | 2018 | 08 | 1000 | 2 | 2 | | 2018 | 09 | 1000 | 2 | 2 | | 2018 | 09 | 1002 | 1 | 2 | +------+------+--------+----------+------+ 4 rows in set (0.03 sec) 解釋: 此處針對1<<d 進行解釋:這裡的計數採取的是點陣圖法,每天有訪問就用1表示,02天表示100,23表示1000..(23個0)。 最後經過bit_or按位或後變成10000..(20個0)100,然後用bit_count統計二進位制1的個數,非常巧妙。