-1

我有两张桌子:

customerschema_id

架构表有:schema_id, period, amt, updated_date

我需要加入客户和模式,但只检索加入的最新记录而不是其他记录。

customer table

cust_id  name schema_id
1        ABC  1

模式表

schema_id  period amt updated_date
1          1      100  2010-4-1
1          2      150  2011-4-1
4

2 回答 2

5

如果您需要max(updated_date)for each schema_id,则可以使用子查询:

select c.cust_id, c.name, c.schema_id, s.period, s.amt, s.updated_date
from customer c
inner join
(
  select s1.schema_id, s1.period, s1.amt, s1.updated_date
  from `schemas` s1
  inner join 
  (
    select schema_id, max(updated_date) MaxDate
    from `schemas`
    group by schema_id
  ) s2
    on s1.schema_id = s2.schema_id
    and s1.updated_date = s2.maxdate
) s
  on c.schema_id = s.schema_id

请参阅带有演示的 SQL Fiddle

然后,子查询用于连接回您的表,以返回具有匹配日期和 schema_id 的行。

于 2013-03-22T19:34:50.767 回答
0

如果我理解您的问题,您需要获取“模式”的最新注册。

我认为您需要使用 max() 函数。因此,请尝试以下查询:

select *
from customer c,
     schema s
where c.schema_id = s.schema_id
  and s.updated_date = ( select max(s2.updated_date)     
                         from schema s2
                         where s2.schema_id = s.schema_id
                       )

问候!

埃德米尔顿

于 2013-03-22T19:44:05.480 回答