当前位置:网站首页>Bit of MySQL_ OR、BIT_ Count function

Bit of MySQL_ OR、BIT_ Count function

2022-07-05 06:21:00 StoNENeee

1. Preface

Recently in to see MySQL Official documents , Find a very clever usage , You can quickly calculate the number of days a user visits the system every month . Now let's analyze the principle .

2. Data preparation

CREATE TABLE data_test (year YEAR, month INT UNSIGNED, day INT UNSIGNED);
INSERT INTO data_test VALUES(2022,1,1),(2022,1,20),(2022,1,30),(2022,2,2),(2022,2,5),(2022,2,5);

From the above table creation statement and data insertion statement 2022 Year of 1 The number of visit days in the month is 3,2 The number of visit days in the month is 2.

According to the general query , You can query according to the following statement :

with a as (select `year`, `month` from data_test group by `year`, `month`)
select b.`year`, b.`month`, count(distinct day) days
from a
    left join data_test b on a.`month` = b.`month` and a.`year` = b.`year`
group by b.`year`, b.`month`;

+------+-------+------+
| year | month | days |
+------+-------+------+
| 2022 |     1 |    3 |
| 2022 |     2 |    2 |
+------+-------+------+

3. Data query

As usual , We need to check twice to get the result . In fact, we have a simpler way to query , Is the use of MySQL For us BIT_ORBIT_COUNT function .

SELECT `year`, `month`, BIT_COUNT(BIT_OR(1 << day)) AS days
FROM data_test
GROUP BY `year`, `month`;

+------+-------+------+
| year | month | days |
+------+-------+------+
| 2022 |     1 |    3 |
| 2022 |     2 |    2 |
+------+-------+------+

You can see that the results obtained are consistent with the results of the above query using the conventional method , So what is the principle of these two functions ? Let's analyze one by one .

  • BIT_OR: This function is used to An operation Medium Or operations Of .

  • BIT_COUNT: This function is used to calculate 1 The number of .

  • 1 << day: Express 1 Moving to the left day bits .

    • 1 << 1 The value is 0000 0000 0000 0000 0000 0000 0000 0010
    • 1 << 20 The value is 0000 0000 0001 0000 0000 0000 0000 0000
    • 1 << 30 The value is 0000 0001 0000 0000 0000 0000 0000 0000

    For this 3 Value for Or operations Words , You can get 0000 0001 0001 0000 0000 0000 0000 0010, take 1 The number of 3

therefore MySQL Get the result through very clever bit operation , It also improves performance .

Last , Welcome to WeChat official account.

原网站

版权声明
本文为[StoNENeee]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202140615004763.html