我有两个表客户和订单,下面是结构。
表格 - 联系人
scrolledFormText.reflow(false);
表 - 订单
id
如何从联系人表中选择所有内容,但只选择订单表中的最新记录?
id
contact_id
但如果我使用SELECT contacts.*,
Max(orders.id)
FROM contacts
LEFT JOIN orders
ON contacts.id = orders.contact_id
GROUP BY contacts.id;
,我总是会NULL
,如果我使用LEFT JOIN
,它只会有价值。
答案 0 :(得分:1)
您可以尝试使用UNION,如
select * from orders order by id desc limit 1
UNION
select * from contacts
答案 1 :(得分:1)
选择订单中的最新记录并将其分组
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
答案 2 :(得分:0)
为了使联系人表格中的所有列聚合最大值,请按功能分组添加联系人表格中的所有列
答案 3 :(得分:0)
我相信Alex提供的答案应该运作良好。以下查询应列出联系人的所有记录和订单表中的最后一个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