2009-01-28 73 views
0

我有一個令人討厭的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!

+0

(了Oracle,SQLServer ..) – FerranB 2009-01-28 12:57:10

回答

6

你可以做s omething這樣的.. RDBMS是否使用的是

 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 
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 
+0

需要添加Users.companyid = Companies.companyid JOIN子句中 – devio 2009-01-28 13:33:35

+0

大抵如此:) – 2009-01-28 16:06:18

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