【问题标题】:How to sort products by price if some products have a discount price (SQL)?如果某些产品有折扣价(SQL),如何按价格对产品进行排序?
【发布时间】:2015-08-22 13:51:28
【问题描述】:

所以我想按价格订购产品 - ASCDESC,但有些产品将在数据库中填写 discountprice 列,如果是这样 - 应该考虑到它们而不是 price 字段。

所以目前我有这个: SELECT * FROM products ORDER BY price ASC,但是我怎样才能为该特定产品的ORDER 子句附加if (discountprice != '' AND discountprice != NULL) then use discount price 之类的内容?

【问题讨论】:

  • 为什么要 discountprice != '' ?不是数字数据类型吗?!?

标签: php mysql sql


【解决方案1】:

使用COALESCE 选择第一个非空值:

SELECT * FROM products
ORDER BY coalesce(discountprice, price) ASC

如果您出于某种原因也将空字符串设为 NULL,请使用常规 CASE

SELECT * FROM products
ORDER BY CASE when discountprice is NOT NULL
                   or discountprice != '' THEN discountprice
              else price end ASC

【讨论】:

    【解决方案2】:

    试试这个

    SELECT * FROM products ORDER BY 
    case when (discountprice != '' or discountprice != NULL) 
    then
      (price-discountprice)
    else
      price
    end 
    ASC
    

    【讨论】:

      【解决方案3】:

      创建虚拟列。当您没有折扣价时,它的列必须为 0。 按此列排序。

      SELECT *,(price - discountprice) as order_price FROM products  ORDER BY order_price ASC
      

      如有必要,您可以强制转换为整数。

      【讨论】:

        【解决方案4】:

        你可以这样做:

        SELECT (price-IFNULL(discountprice,0)) as finalprice FROM products
        ORDER BY finalprice ASC
        

        如果您尝试按discountprice 列订购,您可以通过两种方式进行:

        1. 使用IFNULL

          SELECT * FROM products
          ORDER BY IFNULL(discountprice, price) ASC
          
        2. 使用COALESCE

          SELECT * FROM products
          ORDER BY COALESCE(discountprice, price) ASC
          

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-04-18
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多