MySQL按字母顺序排序

时间:2016-07-27 15:34:12

标签: php mysql sql sql-order-by

我需要按字母顺序排序查询数据,但在某些元素中有数字,排序不是“自然”。

例如:

TABLE
products_id
products_name
product_price 
...

field products_name的值为:

product 1
product 2
product 10
another 4 product
new prod 2
new prod 21
new prod 10

我需要订购这样的记录:

another 4 product
new prod 2
new prod 10
new prod 21
product 1
product 2
product 10

任何人都可以帮助我吗? 谢谢。

3 个答案:

答案 0 :(得分:0)

正确的解决方案是规范您的设计,但只是为了好玩......

    // I declared field owner up at the top here
    class GameViewController: UIViewController, ADBannerViewDelegate, SKPhysicsContactDelegate, SKSceneDelegate, SCNSceneRendererDelegate, SCNPhysicsContactDelegate{

       var fieldOwner = SCNNode()

       override func viewDidLoad() {
          super.viewDidLoad()

         //Force field to act as Gravity 

         fieldOwner = SCNNode()
         fieldOwner.position = SCNVector3(x: 0, y: -5, z: -5)

         let field: SCNPhysicsField = SCNPhysicsField.radialGravityField()
         field.halfExtent = SCNVector3Make(100, 100, 100)
         field.minimumDistance = 20.0
         field.falloffExponent = 0

         self.fieldOwner.physicsField!.strength = 0.0
         self.fieldOwner.physicsField = field

         scnView.scene!.rootNode.addChildNode(fieldOwner)
     }
  }

答案 1 :(得分:-1)

注意:这不是你要求的,但可能还不错

完成自然排序的最佳方法是首先按长度排序,然后按值排序,如此

ORDER BY LENGTH(products_name), products_name

好的,这是另一个荒谬的解决方案,(但它有效)

SELECT * FROM (
SELECT test,
REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(
REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(
    test, 0, ''), 1, ''), 2, ''), 3, ''), 4, ''), 5, '')
    , 6, ''), 7, ''), 8, ''), 9, '') AS derp 
FROM zzz) t1
ORDER BY derp, LENGTH(test), test

注意,为了测试我的解决方案,我实际创建了一个名为zzz的表,其中包含一个名为test的varchar字段,并将实际数据放入其中。它的工作方式与OP要求的完全相同。

答案 2 :(得分:-2)

你应该在你的句子上使用ORDER BY

ORDER BY products_name ASC (or DESC as you want)