当前位置:  开发笔记 > 数据库 > 正文

SQL UNION和ORDER BY

如何解决《SQLUNION和ORDERBY》经验,为你挑选了2个好方法。

我有一个令人讨厌的SQL语句似乎很简单,但它看起来很糟糕.我希望sql返回带有userdata的结果集,以便某个用户是结果集中的第一行,如果用户的emailaddress在公司表中.

我有这个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

它的方式比我的更优雅.谢谢Richard L!



1> 小智..:

你可以这样做..

        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



2> Mladen Prajd..:

这会有用吗?:

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

推荐阅读
周扒pi
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有