mysql 如何根据表1的日期范围是否与表2的日期范围相交进行连接

fhity93d  于 2023-02-21  发布在  Mysql
关注(0)|答案(1)|浏览(119)
left join Mars_Crater_Names n1 on t1.ID=n1.ID and t1.StartDate between n1.StartDate and n1.EndDate

问题是T1中记录的开始日期可能不在StartDateN1中与之匹配的记录的StartDateEndDate之间,因此键入的查询不是我想要的。

N1

| 识别号|火山口名称|开始日期|结束日期|
| - ------|- ------|- ------|- ------|
| ID4|Phoenix|04090000|小行星1822|
| ID4|奥罗拉|小行星1823|小行星1978|

植入物1

| 识别号|恒星_相位|开始日期|结束日期|
| - ------|- ------|- ------|- ------|
| ID4|干燥|小行星1812|小行星1833|
| ID4|正火|小行星1833|小行星1978|
因此,结论是,Phoenix应该与Drying连接,因为它们的值域相交,尽管Aurora确实与Drying相交,但Phoenix是第一个相交的。AuroraNormalizing连接是因为它是第一个也是唯一一个与Normalizing相交的。

left join Mars_Crater_Names n1 on t1.ID=n1.ID and t1.StartDate between n1.StartDate and n1.EndDate

这是我试过的,但离我需要的还差得很远。

umuewwlo

umuewwlo1#

Akina已经给出了交集问题的解决方案,为了只使用第一个匹配项,可以使用row_number() window function,它为partition(类似于group by)生成一个唯一的编号

select * from (
    select
        t1.id as t_id,
        t1.stellar_phase,
        t1.startdate t_startdate,
        t1.enddate t_enddate,
        n1.id as n_id,
        n1.CraterName,
        n1.startdate n_startdate,
        n1.enddate n_enddate,
        row_number() over (partition by t1.stellar_phase order by n1.StartDate) rn
    from stellar_phase t1
    left join Mars_Crater_Names n1 on t1.ID=n1.ID 
    and t1.StartDate <= n1.EndDate
    and n1.StartDate <= t1.EndDate
) x 
where rn = 1

使用以下安装脚本

create table stellar_phase(
  ID    varchar(5),
  Stellar_Phase varchar(20),    
  StartDate  integer,
  EndDate    integer
);

create table Mars_Crater_Names(
  ID    varchar(5),
  CraterName varchar(20),   
  StartDate  integer,
  EndDate    integer
);

insert into Mars_Crater_Names(
  ID,
  CraterName,   
  StartDate,
  EndDate
) values 
('ID4', 'Phoenix',  04090000,   18220000),
('ID4', 'Aurora',   18230000,   19780000);

insert into stellar_phase(
  ID,
  stellar_phase,    
  StartDate,
  EndDate
) values 
('ID4', 'Drying',   18120000,   18330000),
('ID4', 'Normalizing',  18330000,   19780000); -- changed the start date

选择产生
| 测试标识|恒星相|t_开始日期|t_结束日期|n_id|火山口名称|n_开始日期|n_结束日期|伦琴|
| - ------|- ------|- ------|- ------|- ------|- ------|- ------|- ------|- ------|
| ID4|干燥|小行星1812|小行星1833|ID4|Phoenix|小行星409万|小行星1822|1个|
| ID4|正火|小行星1833|小行星1978|ID4|奥罗拉|小行星1823|小行星1978|1个|
注意,我稍微修改了测试数据,因为它与您的描述不匹配。
See the full script on DB Fiddle.

相关问题