All*_*sen 0 sql sorting union select
我有一个令人讨厌的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
Run Code Online (Sandbox Code Playgroud)
顺便说一句,来自用户表的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
Run Code Online (Sandbox Code Playgroud)
它的方式比我的更优雅.谢谢Richard L!
小智 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
Run Code Online (Sandbox Code Playgroud)
这会有用吗?:
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
Run Code Online (Sandbox Code Playgroud)