Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Integer division in MySQL

I have a MySQL table which has a product_id field (big integer)

1102330008 1102330025 1102330070 1103010009 1103010010 1103020006 ...

I want to select rows which have product_id = 110301****. I tried to use this query:

SELECT * FROM `product` WHERE (product_id/10000)=110301  

but it does not return any values with this message:

MySQL returned an empty result set (i.e. zero rows). ( Query took 0.0005 sec )

like image 450
biji buji Avatar asked Jun 29 '12 14:06

biji buji


People also ask

How do you divide in MySQL?

DIV() function : This function in MySQL is used to return a quotient (integer) value when integer division is done. For example, when 7 is divided by 3, then 2 will be returned.

What is integer division operator?

Integer division The % (integer divide) operator divides two numbers and returns the integer part of the result. The result returned is defined to be that which would result from repeatedly subtracting the divisor from the dividend while the dividend is larger than the divisor.

How do you divide two numbers in SQL?

The SQL divide ( / ) operator is used to divide one expressions or numbers by another.


2 Answers

Use the DIV operator.

mysql> SELECT 5 DIV 2;
    -> 2

Integer division. Similar to FLOOR(), but is safe with BIGINT values. Incorrect results may occur for noninteger operands that exceed BIGINT range.

like image 163
djechlin Avatar answered Sep 25 '22 06:09

djechlin


SELECT *
FROM product
WHERE product_id BETWEEN 1103010000
                     AND 1103019999  

If you want to create your query in PHP, then you can construct your query like

$sql = "
    SELECT *
    FROM product
    WHERE product_id BETWEEN {$product_id_range}0000
                         AND {$product_id_range}9999  
";
like image 35
biziclop Avatar answered Sep 25 '22 06:09

biziclop