我有两张桌子。产品表和ProductImage表。产品有唯一的行,ProductImage表有基于ProductImage id的行,名称为product_id(可能是多个)。
积表是
id | product_name
1 | product1
2 | product2ProductImage表是
id | product_id | product_image
1 | 1 | image1
2 | 1 | image2
3 | 1 | image3
4 | 2 | image4
5 | 2 | image5现在,我需要连接product_id中的行,并且只需要基于ProductImages的最后一行product_id。
的结果应该是:
id | product_name | product_id | product_image
1 | product1 | 1 | image3
2 | product2 | 2 | image5请使用我给出的表名以避免混淆。非常感谢你!我要它在拉拉9雄辩或质疑建设者,这取决于你的建议。
发布于 2022-08-25 08:45:50
您没有发布您的MySQL版本,所以我提供两个解决方案:
-- mysql 8 solution
with t as (
select
product_name,
product_id,
product_image,
row_number() over (partition by product_id order by pi.id desc) rn
from products p
left join product_image pi on p.id = pi.product_id
) select product_id, product_name, product_image from t where rn = 1;
-- mysql 5 solution
select
p.product_name,
pi.product_id,
pi.product_image
from products p
join product_image pi on p.id = pi.product_id
join (
select max(id) last_id, product_id from product_image group by product_id
) li on last_id = pi.id;然后你想使用Laravel:
<?php
$query = 'with t as (
select
product_name,
product_id,
product_image,
row_number() over (partition by product_id order by pi.id desc) rn
from products p
left join product_image pi on p.id = pi.product_id
) select product_id, product_name, product_image from t where rn = 1;';
// Select using Laravel
$data = $db::select($db::raw($query));
print_r($data);https://stackoverflow.com/questions/73482067
复制相似问题