简体   繁体   English

mysql BETWEEN将返回0行

[英]mysql BETWEEN will return 0 rows

I have a MySQL table with price structure something like this: 我有一个价格结构像这样的MySQL表:

-------------------- 
| 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? 它不会返回任何行,因为它预计将返回至少3行?

Please note that there are many other rows aswell which are $11,000, and so on... 请注意,还有许多其他行,分别是$ 11,000,依此类推...

Any help would be appreciated! 任何帮助,将不胜感激!

You should be storing it as string or varchar. 您应该将其存储为字符串或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. 如果您是我,我将通过将Price列更改为INTDECIMAL或任何数字(只要是数字)来重组表。

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. “ $ 2999”和“ $ 20000”之间没有任何内容,因为“ $ 2999”>“ $ 20000”按字母顺序排列。

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. 我认为Price是一个文本字段,而不是数字字段。 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. 因此,当您尝试获取介于$ 2999和$ 20000之间的行时,不会返回任何内容,因为与字符串相比,实际上20000小于2999。

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";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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