2012-10-30 35 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; 

这应该工作