Mysql DB w / Street Addresses - 我想按名称排序然后按数字排序?

时间:2015-12-14 16:36:56

标签: php mysql

我很适合为此编写php或mysql。我有一个街道地址如“12-A Test Drive”......我想按地址名称排序整个结果,然后按街道号码排序。我已经想出如何按地址名称排序,但不能正确得到街道号码。

到目前为止,这是我的mysql命令:

SELECT address from property_details ORDER BY SUBSTR(LTRIM(address), LOCATE(' ',LTRIM(address)))

308 Berry Street, 
317 Berry Street, 
803 E. California, 
2046 Lost Thistle Way, 
2000 Lost Thistle Way, 
2019 Lost Thistle Way, 
14 Perry Dr, 
5 Perry Dr, 
10224 Stone Plaza, 
211 Sumney Ave, 
209 Sumney Ave, 
35-B Wicket, 
35-A Wicket, 
317-B Wicket, 
53 Wicket

当我希望它显示如下:

308 Berry Street, 
317 Berry Street, 
803 E. California, 
2000 Lost Thistle Way, 
2019 Lost Thistle Way, 
2046 Lost Thistle Way, 
5 Perry Dr, 
14 Perry Dr, 
10224 Stone Plaza, 
209 Sumney Ave, 
211 Sumney Ave, 
35-A Wicket, 
35-B Wicket, 
53 Wicket, 
317 Wicket

任何帮助都非常感谢!

1 个答案:

答案 0 :(得分:0)

继续使用您已使用的SUBSTRLOCATE功能。您可以通过多种方式ORDER,但如果您需要数字顺序,则需要将字符串更改为数字。这需要拔出连字符(如果存在)。如果你有像#123; 123A Any Street"这样的地址,这将不会起作用。

SELECT
  address,
  CONVERT (
    IF (LOCATE('-', address),
      SUBSTR(TRIM(address), 1, LOCATE('-',TRIM(address)) - 1),
      SUBSTR(TRIM(address), 1, LOCATE(' ',TRIM(address)) - 1)
    ), UNSIGNED
  ) AS number,
  SUBSTR(TRIM(address), LOCATE(' ',TRIM(address))) AS street
FROM property_details
ORDER BY street, number;

http://sqlfiddle.com/#!9/a1775/4