我有两个具有相似字段的表:
表1:
id contact_id |fit_date | model
---|-----------|------------|---------
1 | 10 | 04/03/2009 |Platinum
2 | 10 | 12/01/2010 |Platinum
5 | 12 | 10/03/2019 |Gold
表2:
id contact_id |fit_date | model
---|-----------|------------|---------
1 | 10 | 06/14/2018 |Platinum
2 | 10 | 07/25/2016 |Platinum
5 | 12 | 01/28/2008 |Gold
我需要以某种方式从组合表中返回具有最高fit_date的行,例如,contact_id ='10'。
我需要这样的东西:
id contact_id |fit_date | model
---|-----------|------------|---------
1 | 10 | 06/14/2018 |Platinum
然后稍后当我查询WHERE contact_id = 12时,我会需要这个:
id contact_id |fit_date | model
---|-----------|------------|---------
1 | 12 | 10/03/2018 |Gold
我对这个查询完全迷失了方向,不确定如何开始。
答案 0 :(得分:3)
这是您想要的吗?
select t1.*
from table1 t1
where t1.contact_id = 10
union all
select t2.*
from table2 t2
where t2.contact_id = 10
order by fit_date desc
limit 1;
如果您在每个表的contact_id, fit_date
上都有一个索引,那么这可能会更有效:
(select t1.*
from table1 t1
where t1.contact_id = 10
order by fit_date desc
limit 1
) union all
(select t2.*
from table2 t2
where t2.contact_id = 10
order by fit_date desc
limit 1
)
order by fit_date desc
limit 1;
答案 1 :(得分:0)
似乎您需要统一表的最大数量
select max(fit_date), model , contact_id
from (
select id , contact_id ,fit_date,model
from table1
union
select id , contact_id ,fit_date,model
from table2
) t
group by model , contact_id