首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用laravel-9显示连接表的第一行和父表。

使用laravel-9显示连接表的第一行和父表。
EN

Stack Overflow用户
提问于 2022-08-25 05:02:25
回答 1查看 67关注 0票数 -1

我有两张桌子。产品表和ProductImage表。产品有唯一的行,ProductImage表有基于ProductImage id的行,名称为product_id(可能是多个)。

积表是

代码语言:javascript
复制
id | product_name

1  | product1
2  | product2

ProductImage表是

代码语言:javascript
复制
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。

的结果应该是:

代码语言:javascript
复制
id | product_name | product_id | product_image

1  | product1     |   1        |   image3
2  | product2     |   2        |   image5

请使用我给出的表名以避免混淆。非常感谢你!我要它在拉拉9雄辩或质疑建设者,这取决于你的建议。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-08-25 08:45:50

您没有发布您的MySQL版本,所以我提供两个解决方案:

代码语言:javascript
复制
-- 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;

SQL联机编辑器

然后你想使用Laravel:

代码语言:javascript
复制
<?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);

PHP在线编辑器

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73482067

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档