简体   繁体   English

MySQL-返回第二个表上的最后一条记录,然后返回第一个表中的所有记录

[英]MySQL - Return the last record on the second table then return all in the first table

I have two tables customers and orders, below is the structure. 我有两个表的客户和订单,下面是结构。

Table - contacts 表-联系人

id

Table - orders 表-订单

id
contact_id

How can I select all from contacts table but only select the latest record from the orders table? 如何从联系人表中选择全部,而仅从订单表中选择最新记录?

SELECT contacts.*, 
       Max(orders.id) 
FROM   contacts 
       LEFT JOIN orders 
              ON contacts.id = orders.contact_id 
GROUP  BY contacts.id; 

But I always gets NULL if I use LEFT JOIN , it only have value if I use INNER JOIN . 但是如果我使用LEFT JOIN ,我总会得到NULL ,只有当我使用INNER JOIN它才有价值。

You can try to use UNION like 您可以尝试像

select * from orders order by id desc limit 1
UNION
select * from contacts 

select the latest record in orders and group it first 选择订单中的最新记录并将其首先分组

select contacts.*, orders.id
from contacts
left join (select max(id) as id, contact_id
           from orders
           group by contact_id) orders
     on contacts.id = orders.contact_id


为了汇总联系人表中所有列的最大值,请按功能分组后添加联系人表中的所有列

I trust the answer provided by Alex should work well. 我相信亚历克斯提供的答案应该很好。 The following query shall list all records from contacts and the last id from orders table. 以下查询应列出联系人的所有记录以及订单表中的最后一个ID。

SELECT 
   c.*, 
   (SELECT Max(o.id) FROM orders  o 
    INNER JOIN contacts c1 ON o.id=c1.id
    )as last_order_id
FROM contacts c

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM