简体   繁体   English

SQL-连接同一表

[英]SQL - Joining same table

Let's say I have a table Applications as follows 假设我有一个表Applications如下

ApplicationId INT,
CustomerId INT,
ApplicationDate DATETIME,
IsNewCustomer BOOL

I would like to retrieve a list of applications for a given day along with the IsNewCustomer flag (which is set if no applications are present for the given CustomerId. 我想检索给定日期的应用程序列表以及IsNewCustomer标志(如果给定的CustomerId没有应用程序,则设置该标志。

Currently I am using a join on the same table as follows 目前,我在同一张表上使用联接,如下所示

select 
    o.ApplicationId as ApplicationId,
    cast(o.ApplicationDate as date) as ApplicationDate,
    case when n.ApplicationID is not null then 1 else 0 end as IsNewCustomer,
    row_number() over (partition by o.ApplicationId order by o.ApplicationDate desc) as AppSeqNum
from 
    Applications o 
    left join Applications n 
        on n.CustomerId = o.CustomerId
        and n.ApplicationDate < o.ApplicationDate
where
    AppSeqNum = 1
    and ApplicationDate = getdate()

I was wondering if there is a better way of achieving the same without having to join on the same table as it doesn't 'feel' like the most elegant solution. 我想知道是否有更好的方法来实现相同目的而不必加入同一张表,因为它不像最优雅的解决方案那样“感觉”到。

Thanks! 谢谢!

Well, you might use a sub query, but that will just disguise your self join. 好的,您可以使用子查询,但这只会掩盖您的自我加入。 There is nothing inherently wrong with self joins, they can just get out of hand if you dont have the right indexes and constraints and the table size is limited. 自联接没有内在的错误,如果您没有正确的索引和约束并且表的大小受到限制,它们就可能失控。 One of the reasons you might have heard that self joins are bad is the problem of finding breaks in an otherwise continous monotonic sequence. 您可能听说自连接不好的原因之一是在其他连续单调序列中找到中断的问题。 Say you have a thousand values, with 5 missing and you do a self join (with no indexes or constraints) on value = value +1 then the query optiiser may well decide that there are 1000*1000 possible rows before trying to find the 5 null matches. 假设您有一千个值,而缺少五个,并且对值=值+1进行了自我联接(没有索引或约束),那么查询优化器很可能会确定找到1000 * 1000个可能的行,然后再查找5个空匹配。 So if you have a reasonably limited resuts set then no problem. 因此,如果您的结果集受到合理的限制,那就没问题了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM