简体   繁体   中英

mysql BETWEEN will return 0 rows

I have a MySQL table with price structure something like this:

-------------------- 
| Price | item_id  |
--------------------
|$10,999|  123     |
|$5,889 |  321     |
|$2999  |  143     | 
|------------------|

Now if i Query this :

SELECT * FROM products WHERE price BETWEEN "$2999" AND "$6000";

It will return two rows. But if i Query this :

SELECT * FROM products WHERE price BETWEEN "$2999" AND "$20000";

It won't return any row as it is expected to return atleast 3 rows?

Please note that there are many other rows aswell which are $11,000, and so on...

Any help would be appreciated!

You should be storing it as string or varchar. The way it performs now is it compares for string that's why you have not result. If I were you, I will restructure the table by altering column Price to be INT or DECIMAL , or whatever as long as it is a number.

But to answer your question directly, you can do this but doesn't use any index if you have define one.

WHERE CAST(REPLACE(REPLACE(price,'$',''),',','') AS SIGNED) 
      BETWEEN 2999 AND 20000

It would seem that you are storing the price as a string rather than a number. There is nothing between "$2999" and "$20000" because "$2999" > "$20000" alphabetically.

Here is one way to fix this:

SELECT 
FROM products
WHERE cast(replace(replace(price, '$', ''), ',') as signed) BETWEEN 2999 AND 20000;

A better way would be to store the "price" as a number rather than a character.

I suppose that Price is a text field and not a numeric one. So, when you try to fetch rows between $2999 and $20000 nothing is returned, because actually 20000 is smaller than 2999 when compared as strings.

You must convert the column to a decimal data type with two decimal points.

Drop the $ and leave numbers only. You do not need to save dollar sign with numbers in DB.

SELECT * FROM products WHERE price > 2999 AND price < 6000;
SELECT * FROM products WHERE price > 2999 AND price < 20000;

or

SELECT * FROM products WHERE price BETWEEN 2999 AND 6000";
SELECT * FROM products WHERE price BETWEEN 2999 AND 20000";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM