gpt4 book ai didi

mysql - 使用 2 个表的 Laravel 5.1 查询

转载 作者:行者123 更新时间:2023-11-30 22:31:04 26 4
gpt4 key购买 nike

我有 2 个表:items 和 item_details。

项目:

编号 |姓名 |店铺编号

项目详情:

编号 |项目编号 |价格 |交货 | ...

我需要以最高价格获取所有具有唯一名称的商品。换句话说,我需要从表 2 中为表 1 中的每个唯一名称获取最大价格值。

我尝试使用这个查询,但它只返回 1 行:

$item_details = \DB::table('item_details')
->join('items', 'items.id', '=', 'item_details.item_id')
->where('item_details.price', \DB::raw("(select max(`price`) from item_details)"))
->groupBy('name')
->get();

当我使用 $items = Item::all();$item_details = ItemDetails::all();

                     <tbody>
@if (isset($item_details) && count($item_details))
@foreach($item_details as $detail)
<tr>
<th scope="row" >{{ $detail->item->name}}</th>
<td>{{ $detail->price}}</td>
<td>{{ $detail->delivery}}
</tr>
@endforeach
@else
@endif
</tbody>

我有重复的名字,但我需要每个名字都具有最高价格的唯一名字。Mb 有人知道如何让它变得更容易。

例如:

表 1

id | name | shop_id
1 aaa 1
2 bbb 1
3 ccc 2
4 ddd 1
5 eee 3

表2

id | item_id | price | delivery | ...
1 1 100
2 1 200
3 2 50
4 2 150
5 3 200
6 3 400
7 3 700

结果应该是

name | price |
aaa 200
bbb 150
ccc 700

最佳答案

我认为您查询中的逻辑略有偏差。您的 where 子句表示只返回价格最高的商品。您需要使用 group by 来获取唯一值。

在原始 mysql 中,您的查询应该类似于SELECT max(item_details.price), items.* FROM item_details left join items on item_details.item_id = items.id group by items.name;

编辑:

我认为您正在寻找这样的东西:

$item_details = \DB::table('item_details')
->select(['items.*', \DB::raw('max(`price`)')])
->join('items', 'items.id', '=', 'item_details.item_id')
->groupBy('name')
->get();

关于mysql - 使用 2 个表的 Laravel 5.1 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33895203/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com