0

シンプルに見えてひどい SQL ステートメントがあります。そのユーザーのメールアドレスが会社のテーブルにある場合、特定のユーザーが結果セットの最初の行になるように、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

ちなみに、ユーザーテーブルのメールアドレスは多くの会社にある可能性があるため、メールアドレスに結合することはできません:-(

その声明を改善する方法はありますか?

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!

4

3 に答える 3

6

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

        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
于 2009-01-28T13:02:13.300 に答える
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
于 2009-01-28T12:57:48.787 に答える
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
于 2009-01-28T12:57:52.420 に答える