按最近日期连接两个表

6mzjoqzu  于 2021-06-17  发布在  Mysql
关注(0)|答案(1)|浏览(187)

这个问题在这里已经有答案了

sql仅选择列上具有最大值的行[重复](27个答案)
获取每组分组sql结果的最大值记录(17个答案)
两年前关门了。
我想连接这两个表,显示每个客户最近的到期日:
表“客户”:

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

表“发票”(fk id\客户):

| 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\发票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

我认为有更优雅和更好的表演方式,通过加入。你能给我你的建议吗?
此表结构、数据和查询位于fiddle ps。尽管问题被标记为重复,但其他问题和答案不能解决此问题。

xfb7svmp

xfb7svmp1#

请看这个

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

相关问题