1

我需要编写一个查询来从搜索页面的数据库中选择产品,目前查询真的很简单

SELECT * FROM products WHERE stock > 0 ORDER BY id DESC

此查询从最新开始带回产品,我们将很快开始销售,所以我需要将查询更改为按最新销售的降序排序,然后继续显示剩余的未降序销售的产品。如果产品在售,则 rrp 不等于 0。有没有一种方法可以做到这一点而无需运行两个单独的查询?

是在想像

SELECT * FROM products WHERE stock > 0 ORDER BY (rrp != 0) DESC, id DESC

但这不起作用。

提前致谢

4

5 回答 5

2

您可以按多列排序

SELECT * FROM products WHERE stock > 0 ORDER BY rrp DESC, id DESC

或有 2 个 where

SELECT * FROM products WHERE stock > 0 AND rrp != 0 ORDER id DESC
于 2012-11-26T11:15:47.670 回答
1

试试这个:

SELECT * 
FROM products 
WHERE stock > 0 
ORDER BY 
Case when rrp != 0 then 0 else 1 end,
id DESC
于 2012-11-26T11:18:19.510 回答
0
SELECT * FROM products WHERE stock > 0 and rrp != 0 ORDER BY rrp DESC, id DESC
于 2012-11-26T11:19:03.817 回答
0

您的 RRP 是否像布尔值一样在这里确定产品是否在销售。

请检查以下参考SQLFIDDLE

select * from sale
where stock>0
and rrp <>0
order by stock desc, id

ID  STOCK   RRP
3   490     1
4   200     1
1   120     1

似乎您可能有其他意图,而不是您在此处提到的最简单的要求..

于 2012-11-26T11:23:26.437 回答
0

试试这个

       SELECT * 
              FROM products 
       WHERE stock > 0 

       CASE  WHEN rrp != 0 THEN (ORDER BY rrp DESC) 
       CASE  WHEN rrp= 0   THEN (ORDER BY id DESC)
于 2012-11-26T11:40:57.520 回答