2015-11-28 49 views
0

我想基於OfferTypeSequenceOutofStockPHP MySQL的,排序3山坳的

產品排序結果表看起來像

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)的產品進入頂部並根據sequence(Beta,Charlie,Alpha,Delta)
  2. 然後下一個顯示所有隨機產品,但每次刷新頁面,這些隨機產品洗牌
  3. ,如果產品是outofstock必須留在底部,最後產品

注:如果有offertype所有產品洗牌太當頁面刷新sequence山坳可以去除,但他們必須留在隨機產品的頂部。

我試過的是ORDER BY rand(),ORDER BY FIND_IN_SET()和PHP函數array_rand()但是不能按期望的順序排序產品。

回答

1

這有點棘手,但不是那麼多。首先,您需要進行主要的分類,以便將庫存產品放在底部,隨後是隨機產品組。 但是,你需要一個小訣竅,將不同的分類應用於隨機產品組和具有報價類型的產品組。 您可以通過多種方式解決這個問題,但我認爲情況是最明顯的:

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 

如果我實現你的注意,那麼非隨機的產品能有一個隨機的洗牌也一樣,在這種情況下,你可以簡單排序蘭特()作爲第三個條件:

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

的第一項建議,即使工作,如果'sequence'從'ORDER BY'刪除,'offertype'留在上面,這兩種產品與'offertype'和隨機產品在頁面刷新(這正是目標)洗牌和outofstock留在底部, – Shehary

+0

非常感謝您的幫助。 – Shehary