Raphaël
Raphaël

Reputation: 1141

MySQL order by ... strange order

I've got a little problem with an order by in mysql request.

Here, is my request:

SELECT p.*, 
       pa.`id_product_attribute`, 
       pl.`description`, 
       pl.`description_short`, 
       pl.`available_now`, 
       pl.`available_later`, 
       pl.`link_rewrite`, 
       pl.`meta_description`, 
       pl.`meta_keywords`, 
       pl.`meta_title`, 
       pl.`name`, 
       i.`id_image`, 
       il.`legend`, 
       m.`name` AS manufacturer_name, 
       tl.`name` AS tax_name, 
       t.`rate`, 
       cl.`name` AS category_default, 
       DATEDIFF(
           p.`date_add`, 
           DATE_SUB(NOW(), 
           INTERVAL 0 DAY
       )) > 0 AS new, 
      (p.`price` * IF(t.`rate`,((100 + (t.`rate`))/100),1)) AS orderprice 
      FROM `ps_category_product` cp 
      LEFT JOIN `ps_product` p ON p.`id_product` = cp.`id_product` 
      LEFT JOIN `ps_product_attribute` pa ON (p.`id_product` = pa.`id_product` AND default_on = 1) 
      LEFT JOIN `ps_category_lang` cl ON (p.`id_category_default` = cl.`id_category` AND cl.`id_lang` = 2) 
      LEFT JOIN `ps_product_lang` pl ON (p.`id_product` = pl.`id_product` AND pl.`id_lang` = 2) 
      LEFT JOIN `ps_image` i ON (i.`id_product` = p.`id_product` AND i.`cover` = 1)         
      LEFT JOIN `ps_image_lang` il ON (i.`id_image` = il.`id_image` AND il.`id_lang` = 2) 
      LEFT JOIN `ps_tax_rule` tr ON (p.`id_tax_rules_group` = tr.`id_tax_rules_group` AND tr.`id_country` = 8 AND tr.`id_state` = 0) 
      LEFT JOIN `ps_tax` t ON (t.`id_tax` = tr.`id_tax`) LEFT JOIN `ps_tax_lang` tl ON (t.`id_tax` = tl.`id_tax` AND tl.`id_lang` = 2) 
      LEFT JOIN `ps_manufacturer` m ON m.`id_manufacturer` = p.`id_manufacturer` 
      WHERE cp.`id_category` = 4005 AND p.`active` = 1 ORDER BY p.`location` ASC 

And my result are sort like that :

1,10,11,12,13,14,2,3,4,5,6,7,8,9 ...

In my table, location is defined as un varchar (64). I guess it's the problem... but, I need this field varchar... and I need (sometimes) to sort this field as int value.

Is it possible ?

Thank you for reading

Upvotes: 1

Views: 275

Answers (2)

Tony Hopkinson
Tony Hopkinson

Reputation: 20320

Marco's answer will work as long as the cast does... Another way would be to pad with leading zeros ('01' < '11'), neither are nice though.

Personally though, I'd create a location table, give it a suitable key, use that in related tables and have a location_order column, join and sort.

Upvotes: 0

Marco
Marco

Reputation: 57573

Try this:

ORDER BY CAST(p.location AS SIGNED) ASC

Upvotes: 5

Related Questions