order by子句不能给出我的查询的正确结果

时间:2017-10-27 10:34:10

标签: sql

这是查询

SELECT `properties`.`id` AS `propertyIds` , `properties_field_values`.`property_type_section_field_value` AS `price`
FROM `properties`
INNER JOIN `properties_field_values` ON `properties_field_values`.`property_id` = `properties`.`id`
INNER JOIN `property_type_section_fields` ON `property_type_section_fields`.`id` = `properties_field_values`.`property_type_section_field_id`
WHERE (
`property_type_section_fields`.`field_identifier` = 'basic_price'
)
AND EXISTS (

  SELECT 1
  FROM `property_availaibility`
  INNER JOIN `property_availaibility_dates` ON `property_availaibility_dates`.`property_availaibility_id` = `property_availaibility`.`id`
  WHERE property_availaibility.property_id = properties.id
)
AND (
  `properties`.`property_type_id` =1
)
ORDER BY `price` DESC
LIMIT 0 , 30

当前输出

15  9500
13  850
4   700
5   500
6   300
1   2500
20  2300
16  2000
14  1800
11  1600
12  1550
3   1500
2   1000

我想要什么

15  9500
1   2500
20  2300
16  2000
14  1800
11  1600
12  1550
3   1500
2   1000
13  850
4   700
5   500
6   300

1 个答案:

答案 0 :(得分:0)

以下是使用您的预期值正确排序的示例:

DECLARE @temp TABLE ( id int, price varchar(100))

INSERT INTO @temp VALUES 
(15,  '9500')
,(13,  '850')
,(4,   '700')
,(5,   '500')
,(6,   '300')
,(1,   '2500')
,(20,  '2300')
,(16,  '2000')
,(14,  '1800')
,(11,  '1600')
,(12,  '1550')
,(3,   '1500')
,(2,   '1000')

SELECT * 
  FROM @temp ORDER BY price DESC --ordering as varchar

SELECT id, CAST(price as int) AS price --ordered as decimal
  FROM @temp ORDER BY price DESC

正如其他人提到的那样 properties_field_values.property_type_section_field_value 数据类型是字符串,因此您需要更改表中的数据类型或将选择中的值CAST转换为int:

SELECT 
...
CAST(properties_field_values.property_type_section_field_value AS int) AS price
FROM 
...
)
ORDER BY ...