我有一个烦人的 SQL 语句,看起来很简单,但看起来很糟糕。我希望 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
顺便说一句,用户表中的电子邮件地址可以在许多公司中,因此不能在电子邮件地址上加入:-(
你有什么想法可以改进这个陈述吗?
我正在使用 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
它比我的更优雅。谢谢理查德 L!