SQL UNION和ORDER BY

时间:2009-01-28 12:53:32

标签: sql sorting select union

我有一个令人讨厌的SQL语句看似简单,但看起来很糟糕。 我希望sql返回一个带有userdata的结果集,以便某个用户是结果集中的第一行,如果用户的emailaddress位于公司表中。

我有这个SQL,它返回我想要的东西,但我觉得它看起来很糟糕:

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

顺便说一下,来自用户表的电子邮件地址可以在许多公司中进行,因此无法加入电子邮件地址: - (

您对如何改进该陈述有任何想法吗?

我正在使用Microsoft SQL Server 2000。

编辑: 我正在使用这个:

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

它的方式比我的更优雅。谢谢Richard L!

3 个答案:

答案 0 :(得分:6)

你可以这样做..

        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

答案 1 :(得分:5)

这会有用吗?:

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

答案 2 :(得分:1)

我不确定这是否更好,但这是一种替代方法

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

编辑:如果匹配的不同公司可能有很多电子邮件,并且您只对给定的公司感兴趣,那就变成了

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