我有一个看似简单的烦人的SQL语句,但它看起来awfull。 我想要让某个用户在结果集的第一行,如果用户emailaddress可以在公司表的SQL返回与有序用户数据结果集。

我有这样的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

和的方式,从用户表中EMAILADDRESS可以在许多企业因此不能是在EMAILADDRESS联接: - (

你有什么想法如何改善这种说法?

林使用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

其方式比我更优雅。感谢理查德升!

有帮助吗?

解决方案

您可以做这样的事情..

        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

其他提示

将这项工作:

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

我不知道这是更好的,但它是一种替代方法

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
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top