我正在尝试根据OfferType
Sequence
和OutofStock
对产品进行排序
表格看起来像
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
目标是
- 所有具有
offertype
(Alpha、Bravo、Charlie、Delta)的产品都会出现在顶部,并根据sequence
(Beta、Charlie,Alpha、Delta)进行显示 - 然后接下来显示所有随机产品,但每次页面刷新这些随机产品shuffle
- 如果产品是CCD_ 6,则必须作为最后一个产品保持在底部
注意:如果所有具有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
如果我实现了你的Note,那么非随机产品也可以有随机洗牌,在这种情况下,你可以简单地按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()