SQL UNION e ORDER BY
Domanda
Ho una fastidiosa istruzione SQL che sembra semplice ma sembra orribile. Voglio che sql restituisca un set di risultati con userdata ordinato in modo che un determinato utente sia la prima riga nel set di risultati se l'indirizzo e-mail degli utenti si trova nella tabella delle società.
Ho questo SQL che restituisce quello che voglio ma penso che sia orribile:
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
E comunque, l'indirizzo e-mail dalla tabella degli utenti può essere presente in molte aziende, quindi non ci può essere un join sull'indirizzo e-mail :-(
Hai qualche idea su come migliorare questa affermazione?
Sto usando Microsoft SQL Server 2000.
Modifica: Sto usando questo:
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
È molto più elegante della mia. Grazie Richard L!
Soluzione
Potresti fare qualcosa del genere ..
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
Altri suggerimenti
funzionerà ?:
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
Non sono sicuro che sia meglio, ma è un approccio alternativo
select *, (select count(*) from companies where email = u.email) as o
from users u
order by o desc
Modifica: se ci possono essere molte e-mail tra diverse società corrispondenti e sei interessato solo a quella data società, questo diventa
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