dsoihsnz85757 2013-02-03 22:33
浏览 73
已采纳

MySQL在多列中排名最低

I have a table with the following:

+----+-------+-------+-----------+-----------+--------------+--------------+
| id | stock | price | usedStock | usedPrice | specialStock | specialPrice |
+----+-------+-------+-----------+-----------+--------------+--------------+
| #1 |     1 | 10.00 |         0 | 0         |            0 | 0            |
| #2 |     0 | 0     |         1 | 15.00     |            1 | 20.00        |
| #3 |     0 | 0     |         0 | 11.00     |            1 | 14.00        |
+----+-------+-------+-----------+-----------+--------------+--------------+

I would like to create a query that orders by lowest price first if the type of item is in stock.

So the query would result in the following order:

#1 - 10.00 (because 10.00 is the lowest result)
#3 - 14.00 (because although 11.00 is less, it's not in stock)
#2 - 15.00 (because 15.00 is lower than 20.00)

I've added the PHP tag to this question in case there's a quicker way of calculating using PHP after selecting the table.

  • 写回答

3条回答 默认 最新

  • duanposhi3641 2013-02-03 22:58
    关注

    I would order by the least price, in case item is present in stock:

    ORDER BY
      LEAST(CASE WHEN stock        THEN price        ELSE GREATEST(price, usedPrice, specialPrice) END,
            CASE WHEN usedStock    THEN usedPrice    ELSE GREATEST(price, usedPrice, specialPrice) END,
            CASE WHEN specialStock THEN specialPrice ELSE GREATEST(price, usedPrice, specialPrice) END)
    

    If the condition is true (>=1), each CASE WHEN will return the price, otherwise it will return the greatest price. Fiddle here.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)