mysql中选择另一个表的第一条记录

7jmck4yq  于 2021-06-21  发布在  Mysql
关注(0)|答案(2)|浏览(333)

我´我试图做一个列出所有客户机的查询,并在一个查询中获得history\u client表中的最后一个注解和该注解的日期。

select a.id_client,a.name,a.lastname,(select b.date_created,b.comentary 
from history_of_client b where a.id_client = b.id_client_asociate) from clients_main_table
20jt8wwn

20jt8wwn1#

使用左连接和内连接来获得所需的结果集。

select a.id_client,
       a.name,
       a.lastname,
       hc.date_created,
       hc.comentary
from clients_main_table c
     left join (select id_client_asociate,max(date_created) dt from history_of_client group by id_client_asociate) h
       on (c.id_client = b.id_client_asociate)
     inner join history_of_client hc
       on (hc.id_client_asociate = b.id_client_asociate and hc.date_created = h.date_created)
dw1jzc5e

dw1jzc5e2#

您可以在max(date\u created)上为id\u client在history表和join上使用内部连接

SELECT a.id_client,a.name,a.lastname, h.commentary
FROM clients_main_table a 
INNER join (
  select b.id_client_asociate, max(b.date_created) max_date
  from history_of_client 
  group by  b.id_client_asociate ) t on t.id_client_asociate = a.id_client 
INNER JOIN history_of_client h on h.id_client_asociate = t.id_client_asociate 
      and h.date_created = t.max_date

相关问题