我有一個令人討厭的SQL語句,看起來很簡單,但它看起來不可思議。 我想讓sql返回一個結果集和userdata,這樣如果用戶emailaddress在公司表中,那麼某個用戶是結果集中的第一行。SQL UNION和ORDER BY
我有這樣的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
它的方式比我的更優雅。感謝理查德L!
(了Oracle,SQLServer ..) – FerranB 2009-01-28 12:57:10