如何订购最后库存商品

时间:2016-08-04 10:49:35

标签: mysql sql

我有以下MySQL查询:

SELECT
    *
FROM
    product
INNER JOIN productcontent ON product.id = productcontent.productID
WHERE
    product.deactivate <> '1'
AND productcontent.price > 0 { $level1SQL }
AND menulevel IN ($imploded)
OR menulevel = '$menulevelID' { $level1SQL }
ORDER BY
    (
        CASE
        WHEN discountPrice < price
        AND discountPrice > 0 THEN
            CAST(
                discountPrice AS DECIMAL (10, 2)
            )
        ELSE
            CAST(
                price AS DECIMAL (10, 2)
            )
        END
    ) { $price_order }
LIMIT { $limit }

但我还需要确保如果product.notInStock设置为1,则会在最后订购(但如果选择此类排序,仍然按名称/价格订购),是吗?甚至可能,或者我应该只使用2个查询 - 一个用于库存产品,另一个用于那些不存在的产品?

1 个答案:

答案 0 :(得分:1)

您可以为ORDER BY添加其他密钥:

SELECT *
FROM product p INNER JOIN 
     productcontent pc
     ON p.id = pc.productID
WHERE p.deactivate <> '1' AND
      pc.price > 0 {$level1SQL} AND
      (menulevel IN ($imploded) OR menulevel = '$menulevelID')
      {$level1SQL}
ORDER BY p.not_inStock DESC,
         (case when discountPrice < price and discountPrice > 0
               then CAST(discountPrice AS DECIMAL(10,2))
               else CAST(price AS DECIMAL(10,2)) 
          end) {$price_order}
LIMIT {$limit}

此外,menulevel上的最后一个条件表明您需要括号。