ORDER BY SQL中的两列

时间:2013-06-28 19:29:32

标签: mysql group-by sql-order-by

我有一个非常复杂的查询,我用来从数据库中提取一些结果(数据库设计很脏)。

基本上我最终的结果是按两个标准排序:

  1. t.property
  2. l.unit_number
  3. 基本上我希望将所有类似的t.property分组,然后l.unit_number根据我预先存在的内容进行排序。

    这是我的问题:

    SELECT  t.name_first,
            t.name_middle,
            t.name_last,
            t.tenant_id,
            t.property,
            l.unit_number
    FROM tenants t
    INNER JOIN (
        SELECT  tenant_id, property, unit_number,
                max(lease_start_date) AS newest_start_date
        FROM leases
        GROUP BY property, unit_number
    ) x
    ON t.tenant_id = x.tenant_id
    INNER JOIN leases l
    ON l.lease_start_date = x.newest_start_date
    AND l.tenant_id = t.tenant_id
    WHERE t.name_first != 'Pending'
    AND l.termination_date IS NULL
    ORDER BY l.unit_number REGEXP '^[A-Za-z]+$'
            ,CAST(l.unit_number as SIGNED INTEGER)
            ,CAST(REPLACE(l.unit_number,'-','')AS SIGNED INTEGER)
            ,l.unit_number
            ,t.property
    

    目前我的数据是根据l.unit_number条件进行适当排序,而不是t.property,即:

    t.property      l.unit_number
    4321 Test       1
    1234 Test       2
    5555 Test       3
    4321 Test       4
    1234 Test       7320-1
    4321 Test       7320-2
    5555 Test       7320-3
    5555 Test       7320-4
    1234 Test       A
    4321 Test       B
    4321 Test       C
    5555 Test       D
    

    理想情况下,我希望输出按t.property分组,然后按l.unit_number排序。即:

    t.property      l.unit_number
    1234 Test       2
    1234 Test       7320-1
    1234 Test       A
    4321 Test       1
    4321 Test       4
    4321 Test       7320-2
    4321 Test       B
    5555 Test       3
    5555 Test       7320-3
    5555 Test       7320-4
    5555 Test       D
    

2 个答案:

答案 0 :(得分:2)

将t.property放在ORDER BY

的开头
ORDER BY t.property
    ,l.unit_number REGEXP '^[A-Za-z]+$'
    ,CAST(l.unit_number as SIGNED INTEGER)
    ,CAST(REPLACE(l.unit_number,'-','')AS SIGNED INTEGER)
    ,l.unit_number

答案 1 :(得分:0)

这比这更复杂吗?

ORDER BY t.property
        ,l.unit_number