简体   繁体   中英

Java Mysql Order by Price

I am using Google cloud mysql v.5.5 for a Java based development.

I am trying to order by the resulting data set by price, but until now, prices arent being ordered.

Lets say my query is :

SELECT ID, ITEM_NAME, PRICE FROM REFERENCES .... ORDER BY PRICE ASC

Table References has 4 elements. The prices for those elements are : 1, 12, 12.2 and 2.

When i run the query what i am getting is :

1
12
12.2
2

And i should be getting :

1
2
12
12.2

Any idea what might going on?

Thank you in advance for your time,

Kind regards,

UPDATE1: The field type for PRICE column is VARCHAR as a client prereq, so not much to do about this.

UPDATE2: Price value contains a ',' instead of the usual '.' , so even with the responses i've got until now the results keep being less messy but messy anyways. :(

UPDATE3: Also, i have tried to do the following : ORDER BY replace(PRICE, ',', '')+0 ASC but this also has proven to be unsuccessful. :(

It sounds like price is being stored as a string and not a number.

You can try:

order by price + 0

This will convert it to a number.

Try this:

SELECT ID, ITEM_NAME, PRICE FROM REFERENCES .... 
ORDER BY cast(PRICE as unsigned) ASC

I bet the price column is not numeric but alphanumeric. In that case, the sort order is alphanumeric, so you get

1
12
12.2
2

because 1 < 2 and 12 < 12.2 .

  • First thing to know that.. Google Cloud SQL supports and uses all the features of MySQL 5.5 .
  • MYSQL sorts query results in ascending ORDER BY default.
  • You have to make your PRICE column FLOAT .

SELECT ID, ITEM_NAME, PRICE FROM REFERENCES .... ORDER BY PRICE ASC

Or Simply

SELECT ID, ITEM_NAME, PRICE FROM REFERENCES .... ORDER BY PRICE

And Output- 1 2 12 12.2

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