SQL UNION and ORDER BY

余生颓废 提交于 2019-12-25 14:08:17

问题


I have an annoying SQL statement that seem simple but it looks awfull. I want the sql to return a resultset with userdata ordered so that a certain user is the first row in the resultset if that users emailaddress is in the companies table.

I have this SQL that returns what i want but i think it looks awful:

select 1 as o, * 
from Users u
where companyid = 1
and email = (select email from companies where id=1)
union 
select 2 as o, * 
from Users u
where companyid = 1
and email <> (select email from companies where id=1)
order by o

And by the way, the emailaddress from the user table can be in many companies so there cant be a join on the emailaddress :-(

Do you have any ideas how to improve that statement?

Im using Microsoft SQL Server 2000.

Edit: Im using this one:

select *, case when u.email=(select email from companies where Id=1) then 1 else 2 end AS SortMeFirst 
from Users u 
where u.companyId=1 
order by SortMeFirst

Its way more elegant than mine. Thanks Richard L!


回答1:


You could do something like this..

        select CASE 
                WHEN exists (select email from companies c where c.Id = u.ID and c.Email = u.Email) THEN 1 
                ELSE 2 END as SortMeFirst,   * 
    From Users u 
    where companyId = 1 
    order by SortMeFirst



回答2:


will this work?:

select c.email, * 
from Users u
     LEFT JOIN companies c on u.email = c.email
where companyid = 1
order by c.email desc
-- order by case when c.email is null then 0 else 1 end



回答3:


I am not sure this is better, but it is an alternative approach

select *, (select count(*) from companies where email = u.email) as o 
from users u 
order by o desc

Edit: if there can be many emails across different companies that match, and you are only interested in the given company, this becomes

select *, 
 (select count(*) from companies c where c.email = u.email and c.id = 1) as o 
from users u 
where companyid = 1
order by o desc


来源:https://stackoverflow.com/questions/487515/sql-union-and-order-by

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!