Jump to content

[SOLVED] MYsQL order by problem


JJBlaha

Recommended Posts

I have a list of prices, all the numbered prices start with a  $ sign and some are words.  For example my list might look like

$25
$9
Free
$5.29
$42323
$0.79
Best Offer

I want to sort this list so that the lowest price is on top, then all of the words are at the bottom.  With the default mysql sort (order by price ASC) the list is sorted like this:

$0.79
$25
$42323
$5.29
$9
Best Offer
Free

i want it to be sorted like this:

$0.79
$5.29
$9
$25
$42323
Best Offer
Free

Link to comment
Share on other sites

Because they're strings, they're sorted as strings, which is correct. You could get all of them into an array, take out the $, and sort the numbers in PHP. Then add on the non-numeric ones at the end.

If you post some of your code, we can help you edit it, but you should try on your own first.
Link to comment
Share on other sites

On top of what has been said, you should store the prices in a different column type. I'd recommend DECIMAL. You could then have two other tables. One holding the list of the different deals that can be offered (free, best offer  etc) and another that would hold any relations between specific products and a specific deal.

[code]
item_id, offer_id
1          2
2          1
---------------------
offer_id. offer
1          free
2          best offer
[/code]

This would allow you to remove the deal at any time and the code would automatically show the original marked up price for the item.

To sort them in MYSQL you could use the following however.
[code]
SELECT
*
FROM
tablename
ORDER BY
IF(SUBSTRING(price, 1, 1) = '$', 0, 1) ASC, SUBSTRING(price, 2) + 0 ASC, price ASC
[/code]

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.