MySQL-按最新日期联接两个表

时间:2018-12-29 22:06:59

标签: mysql join

我想加入这两个表,显示每个客户的最新到期日期:

表“客户”:

| id_client |       name |
|-----------|------------|
|         1 | Customer 1 |
|         2 | Customer 2 |
|         3 | Customer 3 |

表格“发票”(FK id_client):

| id_invoice | id_client |   due_date | payment_frequency |
|------------|-----------|------------|-------------------|
|          1 |         1 | 2018-11-30 |           monthly |
|          2 |         1 | 2018-12-30 |           monthly |
|          3 |         2 | 2019-01-01 |         quarterly |
|          4 |         2 | 2019-01-01 |         quarterly |

所需结果:

| id_client |       name |   due_date | payment_frequency |
|-----------|------------|------------|-------------------|
|         1 | Customer 1 | 2018-12-30 |           monthly |
|         2 | Customer 2 | 2019-01-01 |         quarterly |
|         3 | Customer 3 |     (null) |            (null) |

详细信息:

  • 它应该返回所有客户记录,甚至没有发票的记录(空)。

  • 一些客户有多个发票要在同一日期到期(在此示例中,id_invoice 3和4),但是只应返回一条记录。

我能够通过以下查询使它起作用:

SELECT 
    c.id_client,c.name,
    (SELECT due_date FROM invoices WHERE id_client=c.id_client ORDER BY due_date DESC LIMIT 1) AS due_date,
    (SELECT payment_frequency FROM invoices WHERE id_client=c.id_client ORDER BY due_date DESC LIMIT 1) AS payment_frequency
FROM 
  clients AS c

我认为通过联接,有更多优雅且性能更好的方法。能给我您的建议吗?

This table structure, data and query at Fiddle 附言尽管该问题被标记为重复,但其他问题和答案仍无法解决该情况。

1 个答案:

答案 0 :(得分:-1)

请检查一下

select 
  c.id_client,
  c.name,
  max(i.due_date) due_date,
  max(i.payment_frequency) payment_frequency
from clients c
left outer join invoices i
  on c.id_client = i.id_client
group by
  c.id_client,
  c.name

修改:请检查我修改过的答案

select 
  c.id_client,
  c.name,
  i.due_date due_date,
  i.payment_frequency payment_frequency
from clients c
left outer join invoices i
  on c.id_client = i.id_client
where due_date is null or due_date = (select max(due_date) from invoices where id_client = i.id_client)
group by c.id_client, c.name, i.due_date, i.payment_frequency