質問

私は、簡単なようで迷惑なSQL文を持っているが、それはawfull見えます。 私は、ユーザーEMAILADDRESSことが企業のテーブルにある場合、特定のユーザーが結果セットの最初の行になるように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

そしてEMAILADDRESSに参加があり傾けるような方法により、ユーザテーブルからEMAILADDRESSは、多くの企業であることができます: - (

あなたはその文を改善する方法任意のアイデアを持っていますか?

Microsoft SQL Server 2000を使用して

イムます。

編集:

:この1を使用してイム
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!

役に立ちましたか?

解決

あなたはこのような何かを行うことができます..

        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
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top