0

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

基本上我试图通过两个标准订购的最终结果:

  1. t.property
  2. l.unit_number

基本上我希望对所有 liket.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. IE:

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
4

2 回答 2

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
于 2013-06-28T19:36:04.570 回答
0

它比这更复杂吗?

ORDER BY t.property
        ,l.unit_number
于 2013-06-28T19:33:11.883 回答