按两个别名之一排序(对于同一个表的关系)

时间:2016-10-28 20:47:05

标签: sql database postgresql

我有表用户和项目。

项目有:

project_manager_id -> references users.id
business_manager_id -> references users.id

我必须通过其中一个订购。所以,我的查询是:

select * from projects...
LEFT JOIN profiles project_managers ON project_managers.id = projects.project_manager_id
LEFT JOIN profiles business_managers ON business_managers.id = projects.project_manager_id
order by project_managers.name 

OR

order by business_managers.name 

但是对于两个顺序,结果都是一样的。我的结果是由第一个profiles.name JOIN(project_managers.name)订购的。

如何通过project_managers.name或business_manager.name正确订购?

2 个答案:

答案 0 :(得分:0)

这是你想要的吗?

order by coalesce(project_managers.name, business_manager.name)

您使用的是left join,因此假定其中一个值为NULL

答案 1 :(得分:0)

这样的事情会起作用

select * from (
    select projects.id project_id 
    , project_managers.name project_managers_name
    , business_managers.name business_managers_name
    , ...
    from projects
    LEFT JOIN profiles project_managers 
    ON project_managers.id = projects.project_manager_id
    LEFT JOIN profiles business_managers 
    ON business_managers.id = projects.project_manager_id
) projects
order by project_managers_name