SQL并集和排序方式
我有一个恼人的SQL语句,看起来很简单,但看起来太满了。 我希望sql返回一个排序为userdata的resultset,这样,如果某个用户的emailaddress在companys表中,那么该用户就是resultset的第一行 我有一个返回我想要的东西的SQL,但我觉得它看起来很糟糕:SQL并集和排序方式,sql,sorting,select,union,Sql,Sorting,Select,Union,我有一个恼人的SQL语句,看起来很简单,但看起来太满了。 我希望sql返回一个排序为userdata的resultset,这样,如果某个用户的emailaddress在companys表中,那么该用户就是resultset的第一行 我有一个返回我想要的东西的SQL,但我觉得它看起来很糟糕: select 1 as o, * from Users u where companyid = 1 and email = (select email from companies where id=1)
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
它的方式比我的更优雅。谢谢Richard L 这样行吗?:
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
你可以这样做
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
您使用的是哪种RDBMS(Oracle、SQLserver…)您需要在JOIN子句中添加Users.companyid=companyid,注意这不是最佳解决方案,因为您在本例中的select将对每个返回的行运行一次。这可能会导致巨大的性能问题
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