繁体   English   中英

MySQL:使用不同表中的值从组中选择最大值?

[英]MySQL: Select max from group using the value from a different table?

我有两个表,我试图找到按第二个表中的列分组的第一个表中的列的最大值。

这是我的意思的一个例子:

餐桌客户:

customer_id | age
12367       | 23
87693       | 48
66933       | 44
82143       | 38
75454       | 19
38912       | 58
63554       | 80

餐桌采购:

product_id | customer_id
132        | 12367
132        | 66933
132        | 38912
844        | 12367
844        | 63554
598        | 75454
598        | 87693
598        | 66933

我想找到每个产品的最老购买者的 customer_id,例如:

product_id | customer_id | age
132        | 38912       | 58
844        | 63554       | 80
598        | 87693       | 48

我将如何创建一个 mysql 查询来找到它?

使用相关子查询

select product_id , a.customer_id , age
from purchases a inner join customers b on a.customer_id =b.customer_id
where age in (select max(age) from purchases a1 inner join customers b1 on a1.customer_id =b1.customer_id where a.product_id=a1.product_id group by a1.product_id)

暂无
暂无

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

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