MySQL 按两列排序

标签 mysql sql database

我有一个像下面这样的表


    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

你能指出其中的错误吗

最佳答案

试试这个

Select * from Products ORDER BY Featured, Priority

如果您在 mysql 枚举上使用 ORDER BY,它不会按字母顺序排序,但会按其在枚举中的位置排序。

如果您想按照描述的字母顺序排序,请输入枚举名称 像这样的字符串

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

关于MySQL 按两列排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13133208/

相关文章:

php - 如何根据另一个选定的行来选择多行

sql - 这个 MySQL 查询有什么问题?

c# - 在 ASP.NET Web 应用程序上使用 WCF 服务应用程序登录

php - fatal error : Call to a member function bind_param() for login page

php - 我可以用程序风格编写准备好的陈述吗?

mysql - 如何从 SHOW SLAVE STATUS 捕获列值

mysql - 无法加载时区?

mysql - 如何优化IN约束查询?

sql - float 转换为 nvarchar 并限制最大大小

php - 动态表单到数据库