MySQL 中的 LOG2()函数
在本文中,我们将介绍 LOG2()函数,这意味着它将计算以 2 为底的特定数字的对数。
先决条件:LOG函数
MySQL中的LOG2()函数用于计算以2为底的特定数的自然对数,该数必须>0,否则返回NULL。
句法 :
LOG2( X )
范围 :
LOG2()函数接受一个参数,如下所述。
- X –我们要计算其以 2 为底的对数值的数字。它应该是正数。
回报:
它返回给定数字 x 以 2 为底的自然对数。
示例-1:
使用 LOG2()函数以 2 为底的给定数字的对数。
SELECT LOG2(16) AS Log2_Val;
输出 :
Log2_Val |
---|
4 |
Example-2 :
Logarithm of 0 using LOG2() function.
SELECT LOG2(0) AS Log2_Val;
Output :
Log2_Val |
---|
NULL |
Example-3 :
The LOG2 function can also be used to find the logarithmic value with base 2 of a column data. To demonstrate create a table named Product.
CREATE TABLE Product
(
Product_id INT AUTO_INCREMENT,
Product_name VARCHAR(100) NOT NULL,
Buying_price DECIMAL(13,2) NOT NULL,
Selling_price DECIMAL(13,2) NOT NULL,
Service_grade Decimal(6,2) NOT NULL,
PRIMARY KEY(Product_id)
);
Now inserting some data to the Product table :
INSERT INTO Product
(Product_name, Buying_price, Selling_price, Service_grade)
VALUES
('Touring Bike' ,2019.00 ,3009.6 ,0.89 ) ,
('Mountain Bike' ,3019.50 ,4000.56 ,1.00 ) ,
('Road Bike' ,1019.20 ,2000.56 ,-0.89 ) ,
('Road Bicycle',1019.50 ,1500.56 ,-1.50 ) ,
('Racing Bicycle',3019.50 ,4000.56 ,2.00) ;
Showing all data in Product table :
Select * from Product;
Product_id | Product_name | Buying_price | Selling_price | Service_grade |
---|---|---|---|---|
1 | Touring Bike | 2019.00 | 3009.60 | 0.89 |
2 | Mountain Bike | 3019.50 | 4000.56 | 1.00 |
3 | Road Bike | 1019.20 | 2000.56 | -0.89 |
4 | Road Bicycle | 1019.50 | 1500.56 | -1.50 |
5 | Racing Bicycle | 3019.50 | 4000.56 | 2.00 |
Now, we are going to find the logarithmic values with base 2 for all the records present in the Service_grade column.
Select
Product_id,
Product_name,
Buying_price,
Selling_price,
Service_grade,
LOG2(Service_grade) AS GRADELOG2
FROM Product;
Output :
Product_id | Product_name | Buying_price | Selling_price | Service_grade | GRADELOG2 |
---|---|---|---|---|---|
1 | Touring Bike | 2019.00 | 3009.60 | 0.89 | -0.16812275880832692 |
2 | Mountain Bike | 3019.50 | 4000.56 | 1.00 | 0 |
3 | Road Bike | 1019.20 | 2000.56 | -0.89 | NULL |
4 | Road Bicycle | 1019.50 | 1500.56 | -1.50 | NULL |
5 | Racing Bicycle | 3019.50 | 4000.56 | 2.00 | 1 |