2012-10-30 56 views
10

我有一個表像下面mysql命令兩列

 

    CREATE TABLE Products(Product_id INT, ProductName VARCHAR(255), 
          Featured enum('Yes', 'No'), Priority enum('p1', 'p2', 'p3')) 


    INSERT INTO Products(ProductName, Featured, Priority) 
        VALUES('Product A', 'Yes', 'p1'), 
         ('Product B', 'No', 'p2'), 
         ('Product C', 'Yes', 'p1'), 
         ('Product D', 'No', 'p1'), 
         ('Product E', 'Yes', 'p3'), 
         ('Product F', 'No', 'p2'), 
         ('Product G', 'Yes', 'p1'), 
         ('Product H', 'Yes', 'p2'), 
         ('Product I', 'No', 'p2'), 
         ('Product J', 'Yes', 'p3'), 
         ('Product K', 'Yes', 'p1'), 
         ('Product L', 'No', 'p3'); 


我需要的特色產品其次是產品優先P1,P2和P3

 

Op: 
    ProdName | Featured | Priority 

    Product A Yes   p1 
    Product C Yes   p1 
    Product G Yes   p1 
    Product K Yes   p1 
    Product H Yes   p2 
    Product E Yes   p3 
    Product J Yes   p3 
    Product D No   p1 
    Product B No   p2 
    Product F No   p2 
    Product I No   p2 
    Product L No   p3 

我寫了下面的查詢這是不工作..

           
    SELECT * 
    FROM Products 
    ORDER BY Featured IN ('Yes') desc, 
      Priority IN ('p1', 'p2', 'p3') desc 

可以在這

üPLZ點錯誤
+0

你看到了什麼錯誤?你寫的這個陳述應該是有效的,應該是Yogendra Singh推薦的簡化版本。您是否只選擇Product_id列?在你的例子中它將全部爲NULL。 – Yuri

+0

[PHP MySQL按兩列排序]可能的重複(http://stackoverflow.com/questions/514943/php-mysql-order-by-two-columns) –

回答

13

試試這個

Select * from Products ORDER BY Featured, Priority 

如果您在MySQL使用ORDER BY枚舉它不會是按字母順序排序,但它會責令其在枚舉中的位置。

如果你想按字母順序爲您介紹投枚舉名 爲一個字符串這樣

Select * from Products ORDER BY concat(Featured) desc , Priority 
4

你爲什麼不乾脆用SQL爲:

SELECT * 
FROM Products 
    ORDER BY Featured desc, 
     Priority asc; 

通過這樣做YesNo之前就會出現。 P1將在P3之前出現在P2P2之前。我相信,那就是你想要的。

如果數據類型問題再訂貨,

SELECT * 
FROM Products 
    ORDER BY CONCAT(Featured) desc, 
     CONCAT(Priority) asc; 
+0

沒有這不是2工作 – aprilleocean

0

入住這query--

SELECT * 
FROM Products 
    ORDER BY Featured asc,Priority,ProductName asc; 

Fiddle

工作代碼檢查小提琴

-1
SELECT * 
    FROM Products 
where Featured IN ('Yes') and 
     Priority IN ('p1', 'p2', 'p3') 
Order by Featured asc,Priority,ProductName asc; 

這應該工作