doumiang2297 2014-09-23 13:11
浏览 62
已采纳

根据MySQL中ORDER BY的可用性,考虑多列的值

I have 10 price categories.

I have coded everything so that the correct price gets displayed in the price field according to availability. That part works perfectly.

But I don't know how to set the ORDER BY in the query so that all the price fields get into consideration before being sorted.

I have these fields:

'price1`, 'price2`, 'price3`, 'price4`, 'price5`, 'price6`, 'price7`, 'price8`, 'price9`, 'price10`

My current query looks like this:

SELECT * FROM vehicles WHERE `to`='$to' ORDER BY `price1`;

This works when there's only fields from price1 being displayed. however if there's a mixed result of price1 and other price fields, it still only takes price1 into consideration.

I also tried:

SELECT * FROM vehicles WHERE `to`='$to' ORDER BY `price1`, `price2`, `price3`, `price4`, `price5`, `price6`, `price7`, `price8`, `price9`, `price10`;

which failed obviously.

How can I utilize ORDER BY for all these fields at the same time?

Any help is appreciated. Thank you kindly.

  • 写回答

2条回答 默认 最新

  • dongshilve4392 2014-09-23 13:54
    关注
    SELECT * FROM vehicles WHERE `to`='$to' ORDER BY GREATEST(`price1`, `price2`, `price3`, `price4`, `price5`,`price6`,`price7`, `price8`, `price9`, `price10`) DESC
    

    The above should order from the greatest value found in any of the "price" columns all the way down to the smallest value of the row's greatest column.

    Say you have a table

     == Table structure for table test
    
    |------
    |Column|Type|Null|Default
    |------
    |id|int(11)|No|
    |price1|int(11)|No|
    |price2|int(11)|No|
    |price3|int(11)|No|
    == Dumping data for table test
    
    |1|10|20|10
    |2|30|10|10
    |3|100|20|10
    |4|10|10|60
    

    The query

    SELECT * FROM `test` ORDER BY GREATEST(`price1`, `price2`, `price3`) DESC
    

    Will output

    == Dumping data for table test
    
    |3|100|20|10
    |4|10|10|60
    |2|30|10|10
    |1|10|20|10
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值