[英]MySQL - Return the last record on the second table then return all in the first table
我有兩個表的客戶和訂單,下面是結構。
表-聯系人
id
表-訂單
id
contact_id
如何從聯系人表中選擇全部,而僅從訂單表中選擇最新記錄?
SELECT contacts.*,
Max(orders.id)
FROM contacts
LEFT JOIN orders
ON contacts.id = orders.contact_id
GROUP BY contacts.id;
但是如果我使用LEFT JOIN
,我總會得到NULL
,只有當我使用INNER JOIN
它才有價值。
您可以嘗試像
select * from orders order by id desc limit 1
UNION
select * from contacts
選擇訂單中的最新記錄並將其首先分組
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
為了匯總聯系人表中所有列的最大值,請按功能分組后添加聯系人表中的所有列
我相信亞歷克斯提供的答案應該很好。 以下查詢應列出聯系人的所有記錄以及訂單表中的最后一個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.