문제
나는 단순 해 보이지만 끔찍한 것처럼 보이는 성가신 SQL 문이 있습니다. SQL이 사용자 데이터가 주문한 상태에서 resultset을 반환하여 특정 사용자가 endamaddress가 회사 테이블에있는 경우 결과 세트의 첫 번째 행이되도록합니다.
내가 원하는 것을 반환하는이 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을 사용하고 있습니다.
편집 : 이것을 사용하는 IM :
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
내 것보다 더 우아합니다. 감사합니다 Richard L!
해결책
당신은 이런 일을 할 수 있습니다 ..
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
제휴하지 않습니다 StackOverflow