代码之家  ›  专栏  ›  技术社区  ›  Allan Simonsen

SQL UNION和ORDER BY

  •  0
  • Allan Simonsen  · 技术社区  · 17 年前

    我有一个烦人的SQL语句,看起来很简单,但看起来很糟糕。 我希望sql返回一个用户数据有序的结果集,这样,如果某个用户的电子邮件地址在companys表中,则该用户是结果集中的第一行。

    我有一个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上不能有联接:-(

    你有什么想法可以改进这个说法吗?

    我使用的是微软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!

    3 回复  |  直到 17 年前
        1
  •  6
  •   Richard L    17 年前

    你可以做这样的事情。。

            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
  •  5
  •   Mladen Prajdic    17 年前

    这会奏效吗?:

    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
    
        3
  •  1
  •   DanSingerman    17 年前

    我不确定这是否更好,但这是一种替代方法

    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