获取按列值排序的SQL结果

时间:2015-06-19 17:51:54

标签: mysql

我正在尝试按列值排序结果。我有这个基本的查询:

SELECT `product_id`,
       (SELECT `name`
        FROM   `specifications` s
        WHERE  `specification_id` = sp.`specification_id`) AS Specification,
       `value`
FROM   `specs-product` sp
WHERE  `product_id` = '4'
       AND ( `specification_id` = '88'
              OR `specification_id` = '103'
              OR `specification_id` = '18'
              OR `specification_id` = '15'
              OR `specification_id` = '157'
              OR `specification_id` = '89'
              OR `specification_id` = '9'
              OR `specification_id` = '223'
              OR `specification_id` = '224'
              OR `specification_id` = '29'
              OR `specification_id` = '87'
              OR `specification_id` = '219'
              OR `specification_id` = '218'
              OR `specification_id` = '220' ) 

我在表specifications中有一个名为priority的列名。我需要通过此优先级值获取排序结果。

我试图添加order by s.'priority'但是没有用。我怎样才能做到这一点?

表结构如下:

specifications

+------------------+------+----------+
| specification_id | name | priority |
+------------------+------+----------+
| 1                | abc  |        5 |
| 2                | xxxx |        2 |
| 3 ababab         | 3    |          |
+------------------+------+----------+

PRODUCTS

+------------+------------+--+
| product_id | reference  |  |
+------------+------------+--+
|          1 | abc        |  |
|          2 | xxxx       |  |
|          3 | ababab     |  |
+------------+------------+--+

1 个答案:

答案 0 :(得分:1)

添加

order by sp.'priority'

假设它在表中。如果这不起作用,我们需要您的架构。

修改

SELECT `product_id`,
s.name AS Specification,
`value` 
FROM `specs-product` sp 
inner join `specifications` s on s.`specification_id` = sp.`specification_id`
WHERE `product_id`='4' 
AND
(s.`specification_id`='88' or 
s.`specification_id`='103' or 
s.`specification_id`='18' or 
s.`specification_id`='15' or 
s.`specification_id`='157' or 
s.`specification_id`='89' or 
s.`specification_id`='9' or 
s.`specification_id`='223' or 
s.`specification_id`='224' or 
s.`specification_id`='29' or 
s.`specification_id`='87' or 
s.`specification_id`='219' or 
s.`specification_id`='218' or 
s.`specification_id`='220')
order by s.priority