PHP MySQL,按 3 列对结果排序

标签 php mysql sorting mysqli columnsorting

我正在尝试根据 OfferType SequenceOutofStock 对产品进行排序

表格看起来像

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(Alpha、Bravo、Charlie、Delta)的产品均位于顶部并按照序列(Beta、Charlie、Alpha、Delta)显示
  2. 然后接下来显示所有随机产品,但每次页面刷新时这些随机产品都会随机播放
  3. 如果产品缺货,则必须作为最后产品保持在底部。

注意:如果所有具有 offertype 的产品在页面刷新时也会随机播放,则可以删除 sequence col,但它们必须位于随机产品之上.

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

最佳答案

这有点棘手,但也不是那么难。首先,您需要进行初步排序,将缺货产品放在底部,然后是随机产品组。 但是,您需要一些技巧来对随机产品组和具有报价类型的产品组应用不同的排序。 您可以通过多种方式解决这个问题,但我认为一个案例是最明显的:

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

如果我实现你的注释,那么非随机产品也可以进行随机洗牌,在这种情况下,你可以简单地按 rand() 作为第三个条件进行排序:

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()

关于PHP MySQL,按 3 列对结果排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33968471/

相关文章:

PHP内存大小问题

php - 首先根据另一个数组对数组中的值进行排序

php - move_uploaded_file - 防止旋转/忽略 exif 数据

php - 一个月差距计算

Mysql Select with LIKE 子句不工作汉字

mysql - GROUP BY 周返回不正确的结果

mysql - java.sql.SQLSyntaxErrorException : Unknown column . JPA 实体问题?

python - 按 Pandas 数据帧的多索引数据中的索引和值排序

objective-c - 使用多个 NSSortDescriptor 有效地对数组中的对象进行排序

php - 使用正则表达式跳过所有字符,直到使用负先行找到特定的字母序列