选择select - MYSQL中另一个表的第一条记录

时间:2018-05-14 19:08:55

标签: mysql

我正在尝试列出所有客户端的查询,并获取最后的评论和  在单个查询中的history_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

2 个答案:

答案 0 :(得分:0)

使用LEFT JOIN和INNER联接来获得所需的结果集。

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)

答案 1 :(得分:0)

您可以在历史记录表上为id_client使用max(date_created)的内部联接并加入

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