PHP MySQL,按 3 列排序结果
PHP MySQL, Sort result by 3 col's
我正在尝试根据 OfferType
Sequence
和 OutofStock
对产品进行排序
table看起来像
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) 显示
- 然后接下来显示所有随机产品,但每次页面刷新这些 随机产品 随机播放
- 如果产品是
outofstock
,则必须作为 最后一个产品。 留在底部
注意:如果所有具有 offertype
的产品在页面刷新时也随机播放,则可以删除 sequence
列,但它们必须位于 随机产品 之上。
我试过 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()
我正在尝试根据 OfferType
Sequence
和 OutofStock
table看起来像
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) 显示
- 然后接下来显示所有随机产品,但每次页面刷新这些 随机产品 随机播放
- 如果产品是
outofstock
,则必须作为 最后一个产品。 留在底部
注意:如果所有具有 offertype
的产品在页面刷新时也随机播放,则可以删除 sequence
列,但它们必须位于 随机产品 之上。
我试过 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()