首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >PHP,按3 MySQL排序结果

PHP,按3 MySQL排序结果
EN

Stack Overflow用户
提问于 2015-11-28 06:32:34
回答 1查看 46关注 0票数 0

我试图根据OfferType SequenceOutofStock对产品进行分类

这张桌子看起来像

代码语言:javascript
复制
id    name        offertype    sequence    outofstock 
1     Alpha          1             3            0
2     Beta           2             1            0
3     Charlie        3             2            0
4     Delta          4             4            0
5     Random-1       0             5            0
6     Random-2       0             6            0
7     Random-3       0             7            0 
8     Random-4       0             8            0
9     Random-5       0             9            0
10    Random-6       0             10           1

目标是

  1. 所有有offertype的产品(阿尔法,布拉沃,查理,三角洲)都是按照sequence (Beta,Charlie,Alpha,Delta)的方式显示的。
  2. 然后下一个显示所有随机产品,但每次页面刷新这些随机产品洗牌
  3. 如果产品是,outofstock必须保持底部作为最后的产品。

注意:当页面刷新时,如果所有有sequence洗牌的产品都可以被删除,但是它们必须保持在随机产品的顶部。

我尝试过的是ORDER BY rand()ORDER BY FIND_IN_SET()和PHP函数array_rand(),但无法按所需的顺序对产品进行排序。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-11-28 06:38:04

这有点棘手,但没那么多。首先,你需要初级分类把库存产品放在底部,然后是随机产品组。但是,你需要一个小技巧,将不同的分类应用于随机产品组和具有报价类型的产品组。你可以用多种方法解决这个问题,但我认为最明显的是:

代码语言:javascript
复制
ORDER BY
  -- Highest rule. Out of stock products always at the bottom.
  outofstock,
  -- Second important rule, offertype 0 (= random products) go at the bottom
  offertype = 0,
  -- Third rule is combined. Within the groups defined above, you need to sort by different fields.
  -- If offer type = 0 (random), then sort by rand(), else sort by sequence.     
  case when offertype = 0 then
    rand()
  else
    sequence
  end

如果我实现了您的Note,那么非随机产品也可以进行随机洗牌,在这种情况下,您只需将rand()排序作为第三个条件:

代码语言:javascript
复制
ORDER BY
  -- Highest rule. Out of stock products always at the bottom.
  outofstock,
  -- Second important rule, offertype 0 (= random products) go at the bottom
  offertype = 0,
  -- Third rule: within the groups defined above, sort randomly
  rand()
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33968471

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档