mysql left join group by,MySQL LEFT JOIN,GROUP BY和ORDER BY无法按要求工作

I have a table

'products' => ('product_id', 'name', 'description')

and a table

'product_price' => ('product_price_id', 'product_id', 'price', 'date_updated')

I want to perform a query something like

SELECT `p`.*, `pp`.`price`

FROM `products` `p`

LEFT JOIN `product_price` `pp` ON `pp`.`product_id` = `p`.`product_id`

GROUP BY `p`.`product_id`

ORDER BY `pp`.`date_updated` DESC

As you can probably guess the price changes often and I need to pull out the latest one. The trouble is I cannot work out how to order the LEFT JOINed table. I tried using some of the GROUP BY functions like MAX() but that would only pull out the column not the row.

Thanks.

解决方案

It appears that it is impossible to use an ORDER BY on a GROUP BY summarisation. My fundamental logic is flawed. I will need to run the following subquery.

SELECT `p`.*, `pp`.`price` FROM `products` `p`

LEFT JOIN (

SELECT `price` FROM `product_price` ORDER BY `date_updated` DESC

) `pp`

ON `p`.`product_id` = `pp`.`product_id`

GROUP BY `p`.`product_id`;

This will take a performance hit but as it is the same subquery for each row it shouldn't be too bad.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值