首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >SQL在Laravel/PHP中选择有限制的联接

SQL在Laravel/PHP中选择有限制的联接
EN

Stack Overflow用户
提问于 2015-03-04 08:28:25
回答 1查看 1.5K关注 0票数 1

我最初的查询搜索了主板,然后找到了主板的图像。但现在,一些主板没有任何图像关联,所以我想运行一个查询,可以找到20个独特的主板与图像。

目前为止的代码:

代码语言:javascript
复制
$newMotherboards = Motherboards::join('images', 'motherboards.motherboard_id', '=', 'images.item_id')
    ->where('images.item_type', '=', 'motherboard')
    ->orderBy('motherboards.date_added', 'desc')
    ->take(20)
    ->get();

我甚至试着选择具体的结果:

代码语言:javascript
复制
$newMotherboards = Motherboards::join('images', 'motherboards.motherboard_id', '=', 'images.item_id')
    ->select('motherboards.motherboard_id', 'motherboards.name')
    ->where('images.item_type', '=', 'motherboard')
    ->orderBy('motherboards.date_added', 'desc')
    ->take(20)
    ->get();

上面的代码的问题是,当我循环遍历每个$newMotherboards时,它对每一个有ID的图像都有重复。我只想检索20个唯一的主板,它们是最近添加的,但是有图像。

如果一个项目有5个图片,并且是最近增加的20个图片之一,那么它将出现在我的20倍限制的五倍。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-03-04 09:35:43

不同版本:

代码语言:javascript
复制
    $newMotherboards = Motherboards::join('images', 'motherboards.motherboard_id', '=', 'images.item_id')
        ->select('motherboards.motherboard_id', 'motherboards.name')
        ->where('images.item_type', '=', 'motherboard')
        ->distinct()
        ->orderBy('motherboards.date_added', 'desc')
        ->take(20)
        ->get();

Groupby版本:

代码语言:javascript
复制
    $newMotherboards = Motherboards::join('images', 'motherboards.motherboard_id', '=', 'images.item_id')
        ->select('motherboards.motherboard_id', 'motherboards.name')
        ->where('images.item_type', '=', 'motherboard')
        ->groupby('images.item_type')
        ->orderBy('motherboards.date_added', 'desc')
        ->take(20)
        ->get();
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28849719

复制
相关文章

相似问题

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