鍍金池/ 問答/PHP  數據庫/ laravel 去重問題

laravel 去重問題

$coupon->whereIn('id',$res1['coupon_id'])->where('status',2)->get();

//怎么根據merchant_id 來去重

我嘗試了

$coupon->whereIn('id',$res1['coupon_id'])->where('status',2)->groupBy('merchant_id')->get();

結果是
SQLSTATE[42000]: Syntax error or access violation: 1055 Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'run.pq_coupon.id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by (SQL: select * from pq_coupon where pq_coupon.deleted_at is null group by merchant_id)

回答
編輯回答
還吻

審題

題注的需求描述的不是特別清楚,所以根據現(xiàn)有的信息我來完整描述下題主的需求。

題主的表: pq_coupon table , 有幾個核心字段 id,status,merchant_id。

題主嘗試的查詢寫法:

$coupon->whereIn('id',$res1['coupon_id'])->where('status',2)->groupBy('merchant_id')->get();

$coupon->whereIn('id',$res1['coupon_id'])->where('status',2) 會找出一批優(yōu)惠券數據,但是其中 merchant_id 存在很多重復的值。

所以題主想 每個店鋪下(merchant_id) 只找出一條優(yōu)惠券即可。

不知道是否理解正確,正確了再說解題方法。

2017年6月17日 20:39
編輯回答
懷中人

groupby放在get后面

2017年3月25日 09:06
編輯回答
笨小蛋

use DB;

$coupon->select(DB::Raw('DISTINCT(merchant_id)')->whereIn('id',$res1['coupon_id'])->->where('status',2)->get();

2017年11月12日 09:58
編輯回答
熊出沒

如果groupBy不行的話, distict 又該如何書寫代碼?

2017年9月21日 22:08
編輯回答
瘋浪

找到 config/database.php 文件中的 connections -> mysql ;
strict 改為 false ;

具體可以參考 最適合入門的Laravel初級教程(六)

如果你想 知其所以然 ;
我給你個關鍵字 only_full_group_by ;
百之谷之必應之;
搜索一遍你就懂了;

2018年1月27日 17:24
編輯回答
不將就

編輯 config/database.php 第53行 strict的值改成false,我的是5.5的在53行,你看下你的在第幾行,['connections']['mysql']['strict'], 路徑是這樣的

2018年8月11日 01:04
編輯回答
懶豬

這個提示不是說了嗎?
你的數據庫mode有 only_full_group_by 這個就要求你不能用select * 了。
你試試修改數據庫的mode
先 select @@sql_mode;
然后把 only_full_group_by 刪掉;
如果你不能刪的話,就按阿澤說的方法做。

2017年6月19日 13:08